Guarded Suspension Pattern
public class GuardedSuspension {
/**
* Guarded Suspension Pattern【保护悬挂模式】:如果目标对象不在指定的状态下,则执行警戒方法时,
* 当前线程将阻塞等待,直到目标对象进入指定状态为止。
*/
@Test
public void all() throws InterruptedException {
final Disk disk = new Disk();
CompletableFuture.runAsync(() -> new Consumer(disk).consume());
TimeUnit.SECONDS.sleep(2);
new Produer(disk).produce();
TimeUnit.SECONDS.sleep(2);
}
}
@AllArgsConstructor
@Slf4j
class Consumer {
private final Disk disk;
public void consume() {
synchronized (disk) {
if (disk.empty()) {
log.info("current thread is waiting now. {}", Thread.currentThread().getName());
try {
disk.wait();
log.info("take item {}", disk.take());
} catch (final InterruptedException e) {
log.error("Interrupted", e);
}
}
}
}
}
@AllArgsConstructor
class Produer {
private final Disk disk;
public void produce() {
synchronized (disk) {
if (disk.empty()) {
disk.put(Thread.currentThread().getName());
disk.notify();
}
}
}
}
class Disk {
private transient String item;
public boolean empty() {
return StringUtils.isBlank(item);
}
public String take() {
final String take = item;
item = null;
return take;
}
public void put(String item) {
if (StringUtils.isBlank(item)) {
throw new IllegalStateException("invalid item ");
}
this.item = item;
}
}