此題類似于打印循環(huán)打印ABC的問題
下面是實(shí)現(xiàn)方式
private static final Integer FINAL_NUM = 75;
private static Integer Start_NUM = 1;
public static void main(String[] args) throws InterruptedException {
Semaphore a = new Semaphore(1);
Semaphore b = new Semaphore(0);
Semaphore c = new Semaphore(0);
ExecutorService poolService = Executors.newFixedThreadPool(3);
poolService.execute(new Worker(a, b));
poolService.execute(new Worker(b, c));
poolService.execute(new Worker(c, a));
Thread.sleep(1000);
poolService.shutdownNow();
}
public static class Worker implements Runnable {
private Semaphore current;
private Semaphore next;
public Worker(Semaphore current, Semaphore next) {
this.current = current;
this.next = next;
}
public void run() {
while(true) {
try {
// 獲取當(dāng)前的鎖
if(Start_NUM > FINAL_NUM) {
break;
}
current.acquire(); // current - 1
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + "," + Start_NUM++);
}
if(Start_NUM <= FINAL_NUM) {
next.release(); // next + 1
}
} catch (InterruptedException e) {
e.fillInStackTrace();
}
}
}
}