java信号量控制线程打印顺序的示例分享
时间:2023-05-09 12:27:38
import java.util.concurrent.Semaphore;
public class ThreeThread {
public static void main(String[] args) throws InterruptedException {
Semaphore sempA = new Semaphore(1);
Semaphore sempB = new Semaphore(0);
Semaphore sempC = new Semaphore(0);
int N=100;
Thread threadA = new PrintThread(N, sempA, sempB, "A");
Thread threadB = new PrintThread(N, sempB, sempC, "B");
Thread threadC = new PrintThread(N, sempC, sempA, "C");
threadA.start();
threadB.start();
threadC.start();
}
static class PrintThread extends Thread{
int N;
Semaphore curSemp;
Semaphore nextSemp;
String name;
public PrintThread(int n, Semaphore curSemp, Semaphore nextSemp, String name) {
N = n;
this.curSemp = curSemp;
this.nextSemp = nextSemp;
this.name = name;
}
public void run() {
for (int i = 0; i < N; ++i) {
try {
curSemp.acquire();
System.out.println(name);
nextSemp.release();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
}
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java基于Swing实现的打猎射击游戏代码
kafka消费者kafka-console-consumer接收不到数据的解决
![](https://img.aspxhome.com/file/2023/3/116113_0s.png)
如何让java只根据数据库表名自动生成实体类
![](https://img.aspxhome.com/file/2023/2/61322_0s.png)
实例化JFileChooser对象报空指针异常问题的解决办法
![](https://img.aspxhome.com/file/2023/7/132067_0s.png)
Java中用爬虫进行解析的实例方法
Spring spel表达式使用方法示例
IntelliJ IDEA2019实现Web项目创建示例
![](https://img.aspxhome.com/file/2023/3/62333_0s.jpg)
android效果TapBarMenu绘制底部导航栏的使用方式示例
![](https://img.aspxhome.com/file/2023/2/84722_0s.gif)
从零开始学springboot整合feign跨服务调用的方法
![](https://img.aspxhome.com/file/2023/5/81895_0s.png)
利用logback filter过滤某个类 屏蔽某个类
![](https://img.aspxhome.com/file/2023/3/108443_0s.png)
java8 stream 如何打印数据元素
详解Spring boot上配置与使用mybatis plus
解决微服务中关于用户token处理到的坑
java自定义注解实现前后台参数校验的实例
![](https://img.aspxhome.com/file/2023/5/92695_0s.png)
Android保存联系人到通讯录的方法
mybatis使用collection嵌套查询的实现
![](https://img.aspxhome.com/file/2023/1/71861_0s.png)
c# BackgroundWorker使用方法
![](https://img.aspxhome.com/file/2023/1/76411_0s.png)