为了验证synchronized的可见性,编写一下代码:
共享变量的Marker类:
class Marker{
public boolean b;
public Marker(boolean b){
this.b = b;
}
}
线程类:
public class MyThread implements Runnable{
Marker marker;
public MyThread(Marker marker){
this.marker = marker;
}
public void run() {
try{
Thread.sleep(100);
}catch (Exception e){
System.out.println(e.toString());
}
this.marker.b = false;
}
}
主类:
public class synchronizedTest {
public static void main(String[] args) {
Marker marker = new Marker(true);
new Thread(new MyThread(marker)).start();
while(marker.b){
System.out.println("ok");
}
}
}
执行后的结果是:
ok
ok
......
ok
Process finished with exit code 0
多次执行,还是可以得到这个结果,可见,我没有复现出“不可见”的问题。子线程对共享变量marker对象的修改,对于主线程来说是可见的。为什么会这样呢?