package com.zhong.thread;
import java.util.concurrent.Semaphore;
/**
* 使用Semaphore實現三個線程順序打印ABC 5次
*/
public class MultipleThreadRotationUsingSemaphore {
public static void main(String[] args) {
PrintABCUsingSemaphore printABC = new PrintABCUsingSemaphore();
new Thread(() -> printABC.printA()).start();
new Thread(() -> printABC.printB()).start();
new Thread(() -> printABC.printC()).start();
}
}
class PrintABCUsingSemaphore {
private Semaphore semaphoreA = new Semaphore(1);
private Semaphore semaphoreB = new Semaphore(0);
private Semaphore semaphoreC = new Semaphore(0);
private final int TIMES = 5; //順序打印次數
public void printA() {
for (int i = 0; i < TIMES; i++) {
print("A", semaphoreA, semaphoreB);
}
}
public void printB() {
for (int i = 0; i < TIMES; i++) {
print("B", semaphoreB, semaphoreC);
}
}
public void printC() {
for (int i = 0; i < TIMES; i++) {
print("C", semaphoreC, semaphoreA);
}
}
private void print(String name, Semaphore currentSemaphore, Semaphore nextSemaphore) {
try {
currentSemaphore.acquire(1); // currentSemaphore獲取1個許可,如果沒有就阻塞
System.out.println(Thread.currentThread().getName() + " print " + name);
nextSemaphore.release(1); //歸還1個許可給nextSemaphore
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}