不多说,直接看例子,例子是最好的学习方法。
package other.thread8;
public class SyncDemo {
private Boolean flag = true;
public void run() {
while (flag) {
}
System.out.println("已经停止了!");
}
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("已经发起了停止命令!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
image.png
由此可见A线程和B线程flag值没有可视性造成的,而关键字synchronized剧透可视性。
下面将SyncDemo改为:
public class SyncDemo {
private Boolean flag = true;
public void run() {
String str = new String();
while (flag) {
synchronized (str) {
}
}
System.out.println("已经停止了!");
}
public void stop() {
flag = false;
}
}
打印结果:
image.png
网友评论