volatile
public class TestVolatile {
public static volatile boolean flag = true;
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
while (flag) {
}
System.out.println(Thread.currentThread().getName() + " End!");
}, "thread1").start();
Thread.sleep(1000);
System.out.println("flag=false");
flag = false;
}
}
synchronized
需要注意的是synchronized加在while外面并不会起到保持可见性的效果!
可能和synchronized底层实现有关, 如果有大神知道原因欢迎留言告诉博主!
public class TestVolatile {
public static boolean flag = true;
static Object object = new Object();
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
while (flag) {
synchronized (object) {
}
}
System.out.println(Thread.currentThread().getName() + " End!");
}, "thread1").start();
Thread.sleep(1000);
System.out.println("flag=false");
flag = false;
}
}