2 回答

TA貢獻2016條經驗 獲得超9個贊
你可以用Phaser它。關鍵是Phaser制片人問“我錯過了一些消費嗎?” 如果不是,它正在等待,如果是,它會立即繼續進行。這是一個例子:
public class Processor {
private final Phaser phaser = new Phaser(1);
private volatile int lastPhaseId = 0;
public void produce() throws InterruptedException{
System.out.println("inside producer method");
lastPhaseId = phaser.awaitAdvance(lastPhaseId);
System.out.println("thread again wakeup");
}
public void consume() throws InterruptedException{
Thread.sleep(1000);
phaser.arrive();
System.out.println("will i ever be ok ");
}
}
這適用于單個消費者的情況。如果假設有多個消費者,則phase.arrive()需要互斥訪問和/或注冊方相應更改(取決于您需要什么語義)
添加回答
舉報