要求
给定n,m。要求打印从1到n 的数字,并用m个线程去打印,各个线程按顺序交替打印
1. 信号量实现方案
public class MultiThreadPrintNSemaphore {
// 打印数字n
private final int n;
// 打印线程总数
private final int threadCount;
// 信号量
private Semaphore[] semaphores;
public MultiThreadPrintNSemaphore(int n, int threadCount) {
this.n = n;
this.threadCount = threadCount;
this.semaphores = new Semaphore[n];
for (int i = 0; i < this.threadCount; ++i) {
semaphores[i] = new Semaphore(0);
}
semaphores[0].release();
}
public void print() {
for (int i = 0; i < threadCount; ++i) {
new MyThead(i + 1, n, threadCount, semaphores[i], semaphores[(i + 1) % threadCount]).start();
}
}
static class MyThead extends Thread {
// 线程序号
private final int num;
private final int n;