WashingMachine { public void wash() { synchronized (this) { LOGGER.info("{}: Actual machine state: {}", Thread.currentThread().getName(), getWashingMachineState()); if (washingMachineState == WashingMachineState.WASHING) { LOGGER.error("ERROR: Cannot wash if the machine has been already washing!"); return; } washingMachineState = WashingMachineState.WASHING; } LOGGER.info("{}: Doing the washing", Thread.currentThread().getName()); try { Thread.sleep(50); } catch (InterruptedException ie) { ie.printStackTrace(); } endOfWashing(); } WashingMachine(); WashingMachineState getWashingMachineState(); void wash(); synchronized void endOfWashing();  }
@Test public void wash() throws Exception { WashingMachine washingMachine = new WashingMachine(); ExecutorService executorService = Executors.newFixedThreadPool(2); executorService.execute(washingMachine::wash); executorService.execute(() -> { washingMachine.wash(); machineStateGlobal = washingMachine.getWashingMachineState(); }); executorService.shutdown(); try { executorService.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException ie) { ie.printStackTrace(); } assertEquals(WashingMachineState.WASHING, machineStateGlobal); }