boolean isPressed == false; while(isPressed) { // do something }一般都是由变量控制的,事件只是控制变量。
public class Star { /** * @param args */ public static void main(String[] args) { Thread1 thread1 = new Thread1(); thread1.start(); for(int i=0;i<100000000;i++){//这里只是浪费点时间..然后把下面设置成false
} thread1.ok=false; }} class Thread1 extends Thread{ boolean ok =true; @Override public void run() { while(ok){//通过ok变量控制循环. System.out.println("ok"); } System.out.println("while done"); } } To: ...//此处省略n个ok. ok ok ok while done
while(isPressed) {
// do something
}一般都是由变量控制的,事件只是控制变量。
* @param args
*/
public static void main(String[] args) {
Thread1 thread1 = new Thread1();
thread1.start();
for(int i=0;i<100000000;i++){//这里只是浪费点时间..然后把下面设置成false
}
thread1.ok=false;
}}
class Thread1 extends Thread{
boolean ok =true;
@Override
public void run() {
while(ok){//通过ok变量控制循环.
System.out.println("ok");
}
System.out.println("while done");
}
}
To:
...//此处省略n个ok.
ok
ok
ok
while done
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent action)
{
Object state = action.getSource();
if(state == start_stop) {
if(start_stop.isSelected()) {
qq.control = false;
qq.start();
}
else {
qq.control = true;
if(qq.isAlive()) {
qq.stop();
}
}
}
}
}Thread 部分
import java.io.*;
import java.util.*;
class ThreadControl extends Thread {
boolean control = false;
public void run() {
while(true) {
System.out.println("dd");
if(control) {
break;
}
try {
sleep(2 * 1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
这两次过程后 最后的变量要回到 你还没按的时候..注意下. 就是初始化的状态下..这样才不会出错.还有stop方法很早就被废弃了.还是用其他中断的方法..interrupt() 中断线程。
询问一下,变量默认是public的吗?为啥你的Thread部分的Control变量可以在Listener中直接访问呢?另外貌似.stop()的方法没怎么用了吧?好象LZ没有把10楼的例子看明白啊