将lambda传递给计时器而不是TimerTask [英] Passing lambda to a Timer instead of TimerTask

查看:142
本文介绍了将lambda传递给计时器而不是TimerTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在地图上执行延迟的操作,因此我正在使用Timer,我向其中传递了TimerTask和一个延迟(以毫秒为单位):

I want to perform a delayed operation on a map, so I am using Timer, to which I am passing a TimerTask and a delay in milliseconds:

timer.schedule(new TimerTask() {
    public void run() {
        tournaments.remove(id);
    }
}, delay);

这是某种类似于原始缓存的功能,其中我在刚刚创建的新资源上设置了过期时间.

This is some sort of primitive cache-like functionality where I set an expiration time on a new resource that was just created.

我以为我可以使用lambda做到这一点,就像下面这样:

I thought I could do that using lambdas, just like follows:

times.schedule(() -> tournaments.remove(id), delay);

但是编译器说无法做到这一点.为什么?我究竟做错了什么?我可以使用lambda来获得更简洁的代码,还是在这里根本不可能,我应该坚持使用匿名类?

But the compiler says this cannot be done. Why? What am I doing wrong? Could I use lambdas to achieve more concise code or it's simply not possible here and I should stick to an anonymous class?

推荐答案

TimerTask不是SAM(单个抽象方法)类型-现在,这听起来是矛盾的,因为TimerTask上只有一个抽象方法!但是因为抽象父类实现了cancelscheduledExecutionTime,所以即使它们不是抽象的,编译器也无法采取lambda并创建TimerTask的匿名子类型的方法.

TimerTask is not a SAM (single abstract method) type -- now, that sounds contradictory, because there is only one abstract method on TimerTask! But because the abstract parent class implements cancel and scheduledExecutionTime, even though they're not abstract, the compiler can't go so far as to take your lambda and create an anonymous subtype of TimerTask.

可以做的是为具有单个抽象方法和一个或多个 default 方法的接口使用lambda,但遗憾的是TimerTask是一个较旧的类,并且不使用Java 8的默认方法功能

What can be done is lambdas for interfaces that have a single abstract method and one or more default methods, but sadly TimerTask is an older class and doesn't use the default method capabilities of Java 8.

这篇关于将lambda传递给计时器而不是TimerTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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