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

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

问题描述

正如您所知,您可以在Java 8中使用lambdas,例如替换匿名方法。

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?

我想要的是以下内容: / p>

What I wanted is the following:

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?

推荐答案

首先注意计时器实际上是一个过时的API,但很有趣不过你的问题是,你可以在它周围写一个小的包装器来调整 schedule 方法来接受 Runnable ,以及在内部,你将 Runnable 转换为 TimerTask 。然后你会有 schedule 方法接受一个lambda。

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天全站免登陆