int count = 0;
Thread[] threads;
Semaphore[] semaphores;
public void print(int len) throws Exception {
threads = new Thread[len];
semaphores = new Semaphore[len];
for (int i = 0; i < len; i++) {
semaphores[i] = new Semaphore(1);
if (i != len - 1) {
semaphores[i].acquire();
}
}
for (int i = 0; i < len; i++) {
Semaphore lastSemphore = i == 0 ? semaphores[len - 1] : semaphores[i - 1];
Semaphore cur = semaphores[i];
threads[i] = new orderThread(lastSemphore, cur, "线程" + i);
threads[i].start();
}
}
class orderThread extends Thread {
/**
* 每一个线程都保存上一个线程对应的信号量
*/
Semaphore last;
/**
* 保存当前线程的信号量
*/
Semaphore cur;
orderThread(Semaphore last, Semaphore cur, String threadName) {
super(threadName);
this.last = last;
this.cur = cur;
}
/**
* 争夺上个线程的信号量,同时释放当前线程的信号量。这样唤醒下一个线程去争夺当前线程的信号量。
*/
@Override
public void run() {
while (count <= 100) {
try {
last.acquire();
//需要判断,防止线程被唤醒的时候,此时已经超过了100
if (count <= 100) {
System.out.println(Thread.currentThread().getName() + " : " + count++);
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
cur.release();
}
}
}
}
@Test
public void test() throws Exception {
print(3);
Thread.sleep(3000);
}