Thread1中使用wait语句,等待Thread2执行完notify之后,并将synchronized语句块执行完,释放锁之后,Thread1得到重新执行的机会,接着执行下去。
public class Thread1 extends Thread {
private Object lock;
public Thread1(Object lock) {
super();
this.lock = lock;
}
@Override
public void run() {
try {
synchronized (lock) {
System.out.println("wait start=" + System.currentTimeMillis());
lock.wait();
System.out.println("wait end=" + System.currentTimeMillis());
}
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
public class Thread2 extends Thread {
private Object lock;
public Thread2(Object lock) {
super();
this.lock = lock;
}
@Override
public void run() {
try {
synchronized (lock) {
System.out.println("notify start=" + System.currentTimeMillis());
lock.notify();
System.out.println("notify end=" + System.currentTimeMillis());
}
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
public class Test {
public static void main(String[] args) {
try {
Object lock = new Object();
Thread1 t1 = new Thread1(lock);
t1.start();
Thread2 t2 = new Thread2(lock);
t2.start();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
打印结果:
wait start=……
notify start=……
notify end=……
wait end=……
网友评论