题目描述:
三个线程分别打印A,B,C,要求这三个线程一起运行,打印n次,输出形如“ABCABCABC....”的字符串。
在看之前不妨先敲代码试试,看似很简单的问题可能代码写起来没那么顺利。
使用Semaphore:
public class PrintABC {
private int times;
private Semaphore semaphoreA =new Semaphore(1);
private Semaphore semaphoreB =new Semaphore(0);
private Semaphore semaphoreC =new Semaphore(0);
public PrintABC(int times) {
this.times=times;
}
public static void main(String[] args) {
PrintABC PrintABC =new PrintABC(10);
new Thread(PrintABC::printA).start();
new Thread(PrintABC::printB).start();
new Thread(PrintABC::printC).start();
}
public void printA() {
print("A",semaphoreA,semaphoreB);
}
public void printB() {
print("B",sem