java信号量控制线程打印顺序的示例分享

时间:2021-05-19

复制代码 代码如下:
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();
}
}
}

}

}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章