需求:有三个线程轮流执行,第一个线程打印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();
}
}
}
}
本文介绍了一种利用Semaphore实现三个线程按顺序循环打印ABC的方法。通过为每个线程分配一个Semaphore并传递一个Permit,使线程能有序地执行任务。此方案避免了复杂的线程状态管理,代码简洁高效。
:使用Semaphore实现&spm=1001.2101.3001.5002&articleId=78741796&d=1&t=3&u=45d243b3dd6f4a9da3acf65c64044874)
1097

被折叠的 条评论
为什么被折叠?



