Java:参数化的 Runnable

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1659986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 17:28:16  来源:igfitidea点击:

Java: Parameterized Runnable

javagenericscallable

提问by mschayna

Standard Runnableinterface has only non-parametrized run()method. There is also Callable<V>interface with call()method returning result of generic type. I need to pass generic parameter, something like this:

标准Runnable接口只有非参数化run()方法。还有返回泛型类型结果的方法的Callable<V>接口call()。我需要传递泛型参数,如下所示:

interface MyRunnable<E> {
  public abstract void run(E reference);
}
是否有任何标准接口用于此目的,还是我必须自己声明基本接口?

采纳答案by Adamski

Typically you would implement Runnableor Callableas a class that supported a genertic input parameter; e.g.

通常,您将实现RunnableCallable作为支持通用输入参数的类;例如

public class MyRunnable<T> implements Runnable {
  private final T t;

  public MyRunnable(T t) {
    this.t = t;
  }

  public void run() {
    // Reference t.
  }
}

回答by finnw

There is also com.google.common.base.Function<F, T>from Google CollectionsGuava.

还有com.google.common.base.Function<F, T>来自Google Collections Guava

If you set the output type to ?or Void(and always have it return null) you can use it as an alternative to Runnablewith an input parameter.

如果您将输出类型设置为?or Void(并始终让它返回null),您可以将其用作Runnable输入参数的替代方法。

This has the advantage of being able to use Functions.composeto transform the input value, Iterables.transformto apply it to every element of a collection etc.

这具有能够用于Functions.compose转换输入值、Iterables.transform将其应用于集合的每个元素等的优点。

回答by andrewdotn

Java 8 includes the java.util.function.Consumer<T>interface with the single non-default method void accept(T t).

Java 8 包含java.util.function.Consumer<T>具有单个非默认方法的接口void accept(T t)

There are many other related interfaces in that package.

该包中还有许多其他相关接口。

回答by jjnguy

Generally if you wanna pass a parameter into the run()method you will subclass Runnablewith a constructor that takes a parameter.

通常,如果您想将参数传递到run()方法中,您将Runnable使用带有参数的构造函数进行子类化。

For example, You wanna do this:

例如,你想这样做:

// code
Runnable r = new YourRunnable();
r.run(someParam);
//more code

You need to do this:

你需要这样做:

// code
Runnable r = new YourRunnable(someParam);
r.run();
//more code

You will implement YourRunnablesimilar to below:

您将实现YourRunnable类似于以下内容:

public class YourRunnable implements Runnable {
    Some param;
    public YourRunnable(Some param){
        this.param = param;
    }
    public void run(){
        // do something with param
    }
}

回答by Tom Hawtin - tackline

I suggest defining an interface as done in the original question. Further, avoid weak typing by making the interface specific to what it is supposed to do, rather than a meaning-free interface like Runnable.

我建议像原始问题中那样定义一个接口。此外,通过使接口特定于它应该做什么来避免弱类型,而不是像Runnable.

回答by toolkit

Runnable isn't meant to be called directly by client code like foo.run()which would run sequentially in the current thread.

Runnable 并不意味着由客户端代码直接调用,就像foo.run()在当前线程中顺序运行一样。

From the Runnable API:

Runnable API

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run.

This interface is designed to provide a common protocol for objects that wish to execute code while they are active. For example, Runnable is implemented by class Thread. Being active simply means that a thread has been started and has not yet been stopped.

In addition, Runnable provides the means for a class to be active while not subclassing Thread. A class that implements Runnable can run without subclassing Thread by instantiating a Thread instance and passing itself in as the target. In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods. This is important because classes should not be subclassed unless the programmer intends on modifying or enhancing the fundamental behavior of the class.

Runnable 接口应该由其实例旨在由线程执行的任何类实现。该类必须定义一个名为 run 的无参数方法。

该接口旨在为希望在活动时执行代码的对象提供通用协议。例如,Runnable 是由类 Thread 实现的。处于活动状态仅意味着线程已启动且尚未停止。

此外,Runnable 提供了使类处于活动状态而不是子类化 Thread 的方法。通过实例化 Thread 实例并将自身作为目标传入,实现 Runnable 的类可以在不继承 Thread 的情况下运行。在大多数情况下,如果您只打算覆盖 run() 方法而不打算覆盖其他 Thread 方法,则应该使用 Runnable 接口。这很重要,因为除非程序员打算修改或增强类的基本行为,否则类不应被子类化。

Instead, you create a new Thread instance based on your runnable, and then call bar.start(). It is then the JVM's responsibility to call run()in this separate thread.

相反,您根据可运行对象创建一个新的 Thread 实例,然后调用bar.start(). 然后 JVM 负责调用run()这个单独的线程。

Example:

例子:

 public class Foo<E> implements Runnable {
     private final E e;
     public Foo(E e) { ... }
     @Override
     public void run() {
         do something with e.
     }
 }

 Foo<String> foo = new Foo("hello");
 Thread bar = new Thread(foo);
 bar.start();