【问题标题】:functional interface that takes nothing and returns nothing [duplicate]什么都不接受也不返回什么的功能接口[重复]
【发布时间】:2014-05-30 16:03:52
【问题描述】:

JDK 中是否有一个什么都不接受也不返回什么的标准函数式接口?我找不到一个。类似于以下内容:

@FunctionalInterface
interface Action {
  void execute();
}

【问题讨论】:

  • 已经回答并接受,但这是 stackoverflow.com/q/23868733/1441122 的副本。不过,另一个问题有点难找。
  • 确实 - 我编辑了其他问题以使其更通用(即,基于 C# 方法的问题)。

标签: java function java-8


【解决方案1】:

Runnable 怎么样:

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

【讨论】:

  • 是的,就是这样!我忘记了好旧的界面,只看了java.util.function
  • 嗯,public abstract 在界面中?叮叮当当,JDK 人! (以前从未注意到。)
  • FWIW... 虽然它满足功能要求,但听起来不太语义化,Runnable 通常与创建线程相关联。一个带有 doWork 方法的简单 Worker 函数接口会很好。编辑:哎呀:stackoverflow.com/questions/27973294/…
  • 我是这样用Runnable的,然后有人看到这个Runnable,想到“runnable,啊哈,线程”,编辑了代码,fork了一个线程。这导致了一个错误。所以现在我不使用Runnable 作为回调。相关问题(嗯,回答):stackoverflow.com/a/30183786/694469
  • 引用javadoc: The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. 不推荐使用Runnable 只是为了没有参数,返回void的功能接口。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-15
  • 1970-01-01
  • 1970-01-01
  • 2013-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多