java信号量控制线程打印顺序的示例分享
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();
}
}
}
}
}


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




