利用同步锁,这种方式存在问题就是唤醒的过程中不能指定我说需要唤醒的线程,导致同一个锁上的线程都唤醒了,因此条件判断那里使用了while循环
代码如下:
package com.zcj.thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class PrintABC2 {
private int status =1;
public void printA(){
synchronized(this){
while(status!=1){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.print("A");
status=2;
this.notifyAll();
}
}
public void printB(){
synchronized(this){
while(status!=2){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.print("B");
status=3;