新的Runnable和Runnable类型的功能接口有什么区别?

时间:2019-04-17 20:37:35

标签: java multithreading runnable functional-interface

当我创建带有Observable的lambda的Runnable时,代码将按计划执行run方法。但是,如果我创建一个新的Runnable,则代码不会执行该计划,则什么都不会发生?

获取和使用Runnable

的代码
Observable<Usage> usageObservable = Observable.create(emitter -> {
  ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);

  executorService.scheduleAtFixedRate(createNewUsageListener(emitter), 0, 2, TimeUnit.SECONDS);

});

ConnectableObservable<Usage> connectableObservable = usageObservable.share().publish();

connectableObservable.connect();

ScheduledExecutorService时间表工作和执行的代码。

private Runnable createNewUsageListener(ObservableEmitter<Usage> emitter) {
  return () -> {
    List<Usage> usages = getUpdates(rollDice(0, 5));
    if (usages != null) {
      emitUsageStats(emitter, usages);
    }
  };
}

此代码对我来说似乎是相同的代码,但是不会在ScheduledExecutorService

中执行
private Runnable createNewUsageListener(ObservableEmitter<Usage> emitter) {
  return new Runnable() {
    @Override
    public void run() {
      List<Usage> usages = getUpdates(rollDice(0, 5));
      if (usages != null) {
        emitUsageStats(emitter, usages);
      }
    }
  };
}

0 个答案:

没有答案