手机
当前位置:查字典教程网 >编程开发 >Java >java信号量控制线程打印顺序的示例分享
java信号量控制线程打印顺序的示例分享
摘要:复制代码代码如下:importjava.util.concurrent.Semaphore;publicclassThreeThread{p...

复制代码 代码如下:

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();

}

}

}

}

}

【java信号量控制线程打印顺序的示例分享】相关文章:

java中通用的线程池实例代码

在java中使用dom解析xml的示例分析

java向文件末尾添加内容示例分享

java线程并发semaphore类示例

java 实现线程同步的方式有哪些

java实现sunday算法示例分享

java中子类继承父类,程序运行顺序的深入分析

Java排序实现的心得分享

Java线程优先级示例代码

java父类和子类初始化顺序的深入理解

精品推荐
分类导航