阻行设计模式
public class Balking {
/**
* balking design pattern【阻行设计模式】:
* 当目标对象不在特定状态时,执行阻行方法时,该方法会立即返回不执行任何操作。
*/
@Test
public void all() throws InterruptedException {
final int count = 3;
final Machine machine = new Machine();
for (int i = 0; i < count; i++) {
CompletableFuture.runAsync(() -> {
try {
machine.tryRun();
} catch (final InterruptedException e) {
}
});
}
TimeUnit.SECONDS.sleep(5);
}
}
enum MachineState {
IDLE, WORKING
}
@Slf4j
class Machine {
private MachineState state = MachineState.IDLE;
public void tryRun() throws InterruptedException {
synchronized (this) {
if (MachineState.WORKING.equals(state)) {
log.error("machine is working now");
return;
}
state = MachineState.WORKING;
}
log.info("machine is working for {}", Thread.currentThread().getName());
TimeUnit.SECONDS.sleep(2);
finish();
}
private synchronized void finish() {
state = MachineState.IDLE;
log.info("machine is idle now");
}
}