您的位置:首页 > 编程语言 > Java开发

三个线程轮流执行顺序打印ABC(一):使用Semaphore实现

2017-12-07 15:18 453 查看
需求:有三个线程轮流执行,第一个线程打印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();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 线程 semaphore
相关文章推荐