不多說,直接看例子,例子是最好的學(xué)習(xí)方法。
package other.thread8;
public class SyncDemo {
private Boolean flag = true;
public void run() {
while (flag) {
}
System.out.println("已經(jīng)停止了!");
}
public void stop() {
flag = false;
}
}
package other.thread8;
public class ThreadA extends Thread {
private SyncDemo demo;
public ThreadA(SyncDemo demo) {
this.demo = demo;
}
@Override
public void run() {
demo.run();
}
}
package other.thread8;
public class ThreadB extends Thread {
private SyncDemo demo;
public ThreadB(SyncDemo demo) {
this.demo = demo;
}
@Override
public void run() {
demo.stop();
}
}
public class Test {
public static void main(String[] args) {
try {
SyncDemo demo = new SyncDemo();
ThreadA threadA = new ThreadA(demo);
threadA.start();
Thread.sleep(500);
ThreadB threadB = new ThreadB(demo);
threadB.start();
System.out.println("已經(jīng)發(fā)起了停止命令!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

image.png
由此可見A線程和B線程flag值沒有可視性造成的,而關(guān)鍵字synchronized劇透可視性。
下面將SyncDemo改為:
public class SyncDemo {
private Boolean flag = true;
public void run() {
String str = new String();
while (flag) {
synchronized (str) {
}
}
System.out.println("已經(jīng)停止了!");
}
public void stop() {
flag = false;
}
}
打印結(jié)果:

image.png