采用Thread+Semaphore实现,思路很简单

 import java.io.IOException;
import java.util.concurrent.Semaphore; public class PrintABC {
public static int MAX_TIME = 10; public static class PrintThread extends Thread {
private String printChar;
private Semaphore curSemaphore, nextSemaphore; public PrintThread(String printChar, Semaphore curSemaphore,
Semaphore nextSemaphore) {
this.printChar = printChar;
this.curSemaphore = curSemaphore;
this.nextSemaphore = nextSemaphore;
} public void run() {
for (int i = 0; i < MAX_TIME; ++i) {
try {
curSemaphore.acquire(); /* 请求打印需要的信号量,资源数-1,即down操作 */
System.out.println(printChar);
nextSemaphore.release(); /* 释放下一个线程打印需要的信号量,资源数+1,即up操作 */
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
}
} public static void main(String[] args) throws IOException {
Semaphore semaphoreA = new Semaphore(1); /* 只有A信号量的初始资源数为1,保证从A开始打印 */
Semaphore semaphoreB = new Semaphore(0);
Semaphore semaphoreC = new Semaphore(0); new PrintThread("A", semaphoreA, semaphoreB).start();
new PrintThread("B", semaphoreB, semaphoreC).start();
new PrintThread("C", semaphoreC, semaphoreA).start();
}
}

最新文章

  1. html之如何让文字两端对齐
  2. 如何用 fiddler 代理调试本地手机页面
  3. css命名那些事儿
  4. 织梦DedeCMS首页调用单页文档内容的方法
  5. kuangbin_MST A (POJ 1251)
  6. AMQ学习笔记 - 01. 相关背景
  7. 1350. Canteen(map)
  8. flappy bird游戏源代码揭秘和下载
  9. 【C语言探索之旅】 第二部分第五课:预处理
  10. TFS下载文件已损坏问题
  11. Python常用排序算法
  12. Linux命令-基本命令(1)
  13. Redis主从配置和哨兵监控配置——服务器端环境搭建
  14. js 比大小
  15. 【LOJ】#2535. 「CQOI2018」九连环
  16. 如何才能知道外线是FSK还是DTMF制式?
  17. Hive之 数据存储
  18. 会话追踪(session tracking)
  19. Jquery13 Ajax 进阶
  20. threejs 画二维圆(圆弧)

热门文章

  1. Kubernetes资源创建yml语法
  2. sql---如何把sql查询出来的结果当做另一个sql的条件查询,1、语句2、with as
  3. C#自动给文章关键字加链接实现代码
  4. unity里无损实现制定物体bloom
  5. OVN实战---《An Introduction to OVN Routing》翻译
  6. Leetcode 之 Kth Largest Element in an Array
  7. GET和POST请求区别
  8. Linux环境Oracle相关操作命令行
  9. C# 建立UDP服务器并接收客户端数据
  10. 8月自动化测试课程 - Selenium开源自动化测试实践