public static class Thread1 extends Thread{
@Override
public void run() {
synchronized (lock){
System.out.println("this is "+Thread.currentThread().getId());
try {
//模拟工作1
Thread.sleep(1000);
System.out.println(Thread.currentThread().getId()+" begin to wait");
lock.wait();
System.out.println(Thread.currentThread().getId()+" get lock and restart");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getId()+" work complete");
}
}
}
public static class Thread2 extends Thread{
@Override
public void run() {
synchronized (lock){
System.out.println("this is "+Thread.currentThread().getId());
try {
//模拟工作2
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getId()+" egin to notify");
lock.notify();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getId()+" work complete");
}
}
}
public static void main(String[] args) throws InterruptedException {
new Thread1().start();
new Thread2().start();
}
}
运行结果
this is 18
18 begin to wait
this is 19
19 egin to notify
19 work complete
18 get lock and restart
18 work complete
原文:http://blog.51cto.com/mawielbue/2139254