账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    java8: 请问这种写法,为什么可以作为线程对象参数传递?
    • 2019-03-28 00:00
    • 10
    60
    0
    // Java8可以把方法作为参数传递,但是 这个endOfWashing方法并没有返回线程对象啊?为什么可以编译通过呢?
    代码如下,请看wash方法 下面那个参数this::endOfWashing :
      private static final Logger LOGGER = LoggerFactory.getLogger(WashingMachine.class);
      private final DelayProvider delayProvider;
      private WashingMachineState washingMachineState;
    
       public WashingMachine() {
        this((interval, timeUnit, task) -> {
          try {
            Thread.sleep(timeUnit.toMillis(interval));
          } catch (InterruptedException ie) {
            ie.printStackTrace();
          }
          task.run();
        });
      }
    
      /**
       * Creates a new instance of WashingMachine using provided delayProvider. This constructor is used only for
       * unit testing purposes.
       */
      public WashingMachine(DelayProvider delayProvider) {
        this.delayProvider = delayProvider;
        this.washingMachineState = WashingMachineState.ENABLED;
      }
      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());
    
        this.delayProvider.executeAfterDelay(50, TimeUnit.MILLISECONDS, this::endOfWashing);
      }
      /**
       * Method responsible of ending the washing
       * by changing machine state
       */
      public synchronized void endOfWashing() {
        washingMachineState = WashingMachineState.ENABLED;
        LOGGER.info("{}: Washing completed.", Thread.currentThread().getId());
      }
    /**
     * An interface to simulate delay while executing some work.
     */
    public interface DelayProvider {
      void executeAfterDelay(long interval, TimeUnit timeUnit, Runnable task);
    }
    1
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 10 元积分
        全部回答
    • 共 0 条
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部