一个synchronized关键字,能讲一百多页,搞出几十个小举例。
我是服了!
但真的一路演练一下,
对这个关键的应用场景还是了解了很多的。
package test;
public class Service {
private boolean isContinueRun = true;
public void runMethod() {
String anyString = new String();
while (isContinueRun == true) {
synchronized (anyString){
}
}
System.out.println("have stopped.");
}
public void stopMethod() {
isContinueRun = false;
}
}
package test;
public class ThreadA extends Thread {
private Service service;
public ThreadA(Service service) {
super();
this.service = service;
}
@Override
public void run() {
service.runMethod();
}
}
package test;
public class ThreadB extends Thread {
private Service service;
public ThreadB(Service service) {
super();
this.service = service;
}
@Override
public void run() {
service.stopMethod();
}
}
package test;
public class Run {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
try {
Service service = new Service();
ThreadA a = new ThreadA(service);
a.start();
Thread.sleep(1000L);
ThreadB b = new ThreadB(service);
b.start();
System.out.println("have set stop order.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}