如何将 TimerTask 与 lambdas 一起使用? [英] How to use TimerTask with lambdas?

查看:44
本文介绍了如何将 TimerTask 与 lambdas 一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如您所愿,您可以在 Java 8 中使用 lambda,例如替换匿名方法.

As you hopefully know you can use lambdas in Java 8, for example to replace anonymous methods.

可以在此处看到 Java 7 与 Java 8 的示例:

An example can be seen here of Java 7 vs Java 8:

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        checkDirectory();
    }
};

在 Java 8 中可以表示为以下两种方式:

Can be expressed as both the following ways in Java 8:

Runnable runnable = () -> checkDirectory();

Runnable runnable = this::checkDirectory;

这是因为 Runnable 是一个函数式接口,只有一个(抽象的)公共非默认方法.

This is because Runnable is a functional interface, having only one (abstract) public non-default method.

然而......对于TimerTask,我们有以下内容:

However... For TimerTask we have the following:

TimerTask timerTask = new TimerTask() {
    @Override
    public void run() {
        checkDirectory();
    }
};

看起来很眼熟吧?
但是使用 lambda 表达式不起作用,因为 TimerTask 是一个抽象类,即使它只有一个抽象的公共非默认方法,它也不是一个接口,因此也没有功能接口.
它也没有被重构为具有默认实现的接口,因为它携带状态,因此无法完成.

Looks familiar, right?
Using a lambda expression does not work though, because TimerTask is an abstract class, even though it has only one abstract public non-default method, it is not an interface and hence no functional interface either.
It is also not refactored into an interface with default implementations, because it carries state, so that cannot be done then.

所以我的问题:在构建 TimerTask 时有没有办法使用 lambdas?

So my question: Is there any way to use lambdas when constructing the TimerTask?

我想要的是以下内容:

Timer timer = new Timer();
timer.schedule(this::checkDirectory, 0, 1 * 1000);

有什么办法可以让它变得更好,而不是一些丑陋的匿名内部类?

Instead of some ugly anonymous inner class, is there any way to make it nicer?

推荐答案

首先要注意 Timer 实际上是一个过时的 API,但尽管如此,还是可以娱乐您的问题,您可以围绕它编写一个小包装器调整 schedule 方法以接受 Runnable,然后在内部将 Runnable 转换为 TimerTask.然后,您将拥有接受 lambda 的 schedule 方法.

Noting first that Timer is effectively an antiquated API, but entertaining your question nevertheless, you could write a small wrapper around it which would adapt the schedule method to accept a Runnable, and on the inside you'd turn that Runnable into a TimerTask. Then you would have your schedule method which would accept a lambda.

public class MyTimer {
  private final Timer t = new Timer();

  public TimerTask schedule(final Runnable r, long delay) {
     final TimerTask task = new TimerTask() { public void run() { r.run(); }};
     t.schedule(task, delay);
     return task;
  }
}

这篇关于如何将 TimerTask 与 lambdas 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆