在线程获取到锁对象后,执行锁对象的wait()。当前线程将释放锁并加入锁对象的等待队列,其他线程调用锁对象的notify()、notifyAll(),则将之前加到等待队列的线程改变到锁对象的就绪队列中。等到CPU轮转到这个线程,就继续执行输出。
public static void main(String[] args) throws InterruptedException {
Object o = new Object();
Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0;i<50 ;i++){
synchronized (o){
System.out.println(Thread.currentThread().getName()+"线程一"+i);
o.notify();
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}});
Thread threadB = new Thread(new Runnable() {
@Override
public void run() {
for(int j = 0; j<50 ;j++){
synchronized (o){
System.out.println(Thread.currentThread().getName()+"线程二"+j);
o.notify();
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}});
threadA.start();
Thread.sleep(100);
threadB.start();
}