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