package com.espen.exer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author espen_tian
* @version v1.0
* @description 交替打印ABC
* @date 2019-12-15 19:43
*/
public class AlternateTest {
public static void main(String[] args) {
Resource resource = new Resource();
new Thread(() -> {
for (int i = 1; i <= 10; i++) {
resource.printA(i);
}
}).start();
new Thread(() -> {
for (int i = 1; i <= 10; i++) {
resource.printB(i);
}
}).start();
new Thread(() -> {
for (int i = 1; i <= 10; i++) {
resource.printC(i);
}
}).start();
}
}
//共享资源
class Resource {
//线程标记,作为判断是否打印的依据
private int number = 1;
//锁对象
private Lock lock = new ReentrantLock();
private Condition cond1 = lock.newCondition();
private Condition cond2 = lock.newCondition();
private Condition cond3 = lock.newCondition();
/**
* 打印A的方法
*
* @param loopNum 当前第loopNum轮打印
*/
public void printA(int loopNum) {
try {
lock.lock();//加锁
if (number != 1) {
cond1.await();
}
System.out.print("A" + loopNum + "\t");
number = 2;
cond2.signal();//唤醒打印B的线程
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();//释放锁
}
}
/**
* 打印B的方法
*
* @param loopNum 当前第loopNum轮打印
*/
public void printB(int loopNum) {
try {
lock.lock();//加锁
if (number != 2) {
cond2.await();
}
System.out.print("B" + loopNum + "\t");
number = 3;
cond3.signal();//唤醒打印C的线程
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();//释放锁
}
}
/**
* 打印C的方法
*
* @param loopNum 当前第loopNum轮打印
*/
public void printC(int loopNum) {
try {
lock.lock();//加锁
if (number != 3) {
cond3.await();
}
System.out.print("C" + loopNum+"\t");
number = 1;
cond1.signal();//唤醒打印A的线程
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();//释放锁
}
}
}
执行结果