三個執行緒輪流執行順序列印ABC(一):使用Semaphore實現
阿新 • • 發佈:2019-01-05
需求:有三個執行緒輪流執行,第一個執行緒列印A,第二個執行緒列印B,第三個執行緒列印C……迴圈10次。
思路:三個執行緒對應三個Semaphore,三個Semaphore維護一個Permit。當前執行緒通過對應的Semaphore獲取Permit,執行列印,並通過下一個執行緒對應的Semaphore釋放Permit。類似於Permit在當前的執行緒對應的Semaphore中,傳遞到了下一個執行緒對應的Semaphore中。下一個執行緒通過對應的Semaphore獲取Permit,繼續執行……迴圈10次。
效率:每個執行緒使用一個Semaphore,一個Permit在不同的Semaphore之間迴圈傳遞,當前執行緒消費完Permit後,無法立即進行下一次列印,而下一個執行緒使用的Semaphore剛好獲取到了Permit,從而使執行緒可以交替執行。不需要額外的執行緒輪流狀態state欄位。程式碼簡潔,效率高。
實現程式碼:
package edu.self.multithread;
import java.util.concurrent.Semaphore;
/**
* Created by SunYanhui on 2017/12/4.
*/
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 int attempts = 0;
public void printA() {
print("A", semaphoreA, semaphoreB);
}
public void printB() {
print("B", semaphoreB, semaphoreC);
}
public void printC() {
print("C", semaphoreC, semaphoreA);
}
private void print(String name, Semaphore currentSemaphore, Semaphore nextSemaphore) {
for (int i = 0; i < 10; ) {
try {
currentSemaphore.acquire();
//System.out.println(Thread.currentThread().getName()+" try to print "+name+", attempts : "+(++attempts));
System.out.println(Thread.currentThread().getName() +" print "+ name);
i++;
nextSemaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}