使用ReentrantLock+Condition同样可以实现经典模式生产者/消费者模式
开始测试
1. 两个线程一对一交替执行
线程交替执行的方法
public class TestPC {
private volatile boolean printA = true;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void printA(){
try {
lock.lock();
while(printA) {
condition.await();
}
System.out.println("AAAAA");
printA = true;
condition.signal();
} catch (InterruptedException e){
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printB(){
try {
lock.lock();
while(!printA) {
condition.await();
}
System.out.println("BBBBB");
printA = false;
condition.signal();
} catch (InterruptedException e){
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
线程类
public class TestPCThreadA extends Thread{
private TestPC testPC;
public TestPCThreadA(TestPC testPC){
super();
this.testPC = testPC;
}
@Override
public void run(){
for (int i = 0; i < 10; i++){
testPC.printA();
}
}
}
public class TestPCThreadB extends Thread{
private TestPC testPC;
public TestPCThreadB(TestPC testPC){
super();
this.testPC = testPC;
}
@Override
public void run(){
for (int i = 0; i < 10; i++){
testPC.printB();
}
}
}
测试类
public class TestPCMain {
public static void main(String[] args){
TestPC testPC = new TestPC();
Thread threadA = new TestPCThreadA(testPC);
Thread threadB = new TestPCThreadB(testPC);
threadA.start();
threadB.start();
}
}
运行结果
2. 多线程打印AB交替执行
修改同步对象的打印内容,注意,为防止出现假死现象,使用signalAll()方法。
public class TestPC {
private volatile boolean printA = true;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void printA(){
try {
lock.lock();
while(printA) {
condition.await();
}
System.out.println("Thread---A" + Thread.currentThread().getName() + "---AAAAA");
printA = true;
condition.signalAll();
} catch (InterruptedException e){
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printB(){
try {
lock.lock();
while(!printA) {
condition.await();
}
System.out.println("Thread---B" + Thread.currentThread().getName() + "---BBBBB");
printA = false;
condition.signalAll();
} catch (InterruptedException e){
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
去掉线程类中的循环调用方法A、B
public void run(){
//for (int i = 0; i < 10; i++){
testPC.printA();
//}
}
public void run(){
//for (int i = 0; i < 10; i++){
testPC.printB();
//}
}
测试类
public class TestPCMain {
public static void main(String[] args){
TestPC testPC = new TestPC();
for(int i = 0; i < 10; i++){
Thread threadA = new TestPCThreadA(testPC);
threadA.setName(String.valueOf(i));
threadA.start();
Thread threadB = new TestPCThreadB(testPC);
threadB.setName(String.valueOf(i));
threadB.start();
}
}
}
运行结果