本文主要是介绍设计模式 Concurrency 之 Balking 慢行模式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
- 定义
- 例子
1.定义
当现在不适合这个操作,或者没有必要进行这个操作时,就直接放弃而回去
2.例子
WashinMachineState
package com.hqq.concurrency.balking;/*** WashingMachineState* Created by heqianqian on 2017/7/30.*/
public enum WashingMachineState {ENABLED, WASHING;}
WashingMachine
package com.hqq.concurrency.balking;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;/*** WashingMachine* Created by heqianqian on 2017/7/30.*/
public class WashingMachine {private static final Logger LOGGER = LoggerFactory.getLogger(WashingMachine.class);private WashingMachineState washingMachineState;public WashingMachine() {this.washingMachineState = WashingMachineState.ENABLED;}public void wash() {synchronized (this) {if (washingMachineState == WashingMachineState.WASHING) {LOGGER.info("{}: Error:Machine is Running");return;}washingMachineState = WashingMachineState.WASHING;}LOGGER.info("{} is Washing..", Thread.currentThread().getName());try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}endOfWashing();}private synchronized void endOfWashing() {LOGGER.info("{} Finished Washing", Thread.currentThread().getName());washingMachineState = WashingMachineState.ENABLED;}public WashingMachineState getWashingMachineState() {return washingMachineState;}
}
APP
package com.hqq.concurrency.balking;import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;/*** App* Created by heqianqian on 2017/7/30.*/
public class App {public static void main(String... args) {final WashingMachine washingMachine = new WashingMachine();ExecutorService executorService = Executors.newFixedThreadPool(3);executorService.execute(washingMachine::wash);executorService.execute(washingMachine::wash);executorService.execute(washingMachine::wash);executorService.shutdown();}
}
测试结果:
INFO [2017-08-09 01:17:56,169] com.hqq.concurrency.balking.WashingMachine: {}: Error:Machine is Running
INFO [2017-08-09 01:17:56,169] com.hqq.concurrency.balking.WashingMachine: pool-1-thread-1 is Washing..
INFO [2017-08-09 01:17:56,169] com.hqq.concurrency.balking.WashingMachine: {}: Error:Machine is Runningcom.hqq.concurrency.balking.WashingMachine: pool-1-thread-1 Finished Washing
这篇关于设计模式 Concurrency 之 Balking 慢行模式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!