java信号量控制线程打印顺序的示例分享
java信号量控制线程打印顺序的示例分享
发布时间:2016-12-28 来源:查字典编辑
摘要:复制代码代码如下: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学习
编程开发子分类