class Service {
private String anyString = new String();
public void a() throws InterruptedException {
synchronized (anyString) {
System.out.println("a begin");
Thread.sleep(3000);
System.out.println("a end");
}
}
public void b() {
synchronized (this) {
System.out.println("b begin");
System.out.println("b end");
}
}
}
class ThreadA implements Runnable {
private Service service;
public ThreadA(Service service) {
this.service = service;
} @Override public void run() {
try {
service.a();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class ThreadB implements Runnable {
private Service service;
public ThreadB(Service service) {
this.service = service;
} @Override public void run() {
service.b();
}
}
public class Main {
public static void main(String[] args) {
Service service = new Service();
new Thread(new ThreadA(service)).start();
new Thread(new ThreadB(service)).start();
}
} 最终输出结果: