62,614
社区成员
发帖
与我相关
我的任务
分享
while (!this.done)
Thread.sleep(1000);
public class Test {
boolean flag = true;
public static void main(String[] args) {
Test t =new Test();
t.test();
t.test2();
}
void test(){
new Thread(){
@Override
public void run() {
try {
sleep(3000);
flag = false;
} catch (InterruptedException e) {
e.printStackTrace();
}
};
}.start();
}
void test2(){
while (flag){
try {
Thread.sleep(1000);
System.out.println("xxxxx");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private volatile static boolean stop;
也可保证volatile boolean flag = true;//使用volatile修饰
public class Visibility {
private static boolean stop;
public static void main(String[] args) throws Exception {
new Thread(new Runnable(){
public void run() {
int i = 0;
while(!stop) {
i++;
}
System.out.println("finish loop,i=" + i);
}
}).start();
Thread.sleep(1000);
stop = true;
Thread.sleep(2000);
System.out.println("finish main");
}
}