繁体   English   中英

我们如何将可调用对象转换为可运行对象

[英]How can we convert a callable into a runnable

我有一个实现可调用接口的类。 我想使用 ScheduledExecutorService 接口的 scheduleAtFixedRate 方法为类安排任务。 然而 scheduleAtFixedRate 需要一个可运行的对象作为它可以调度的命令。

因此,我需要某种方式将可调用对象转换为可运行对象。 我尝试了简单的铸造,但这不起作用。

示例代码:

package org.study.threading.executorDemo;

import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

class ScheduledExecutionTest implements Callable<String> {

    @Override
    public String call() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("inside the call method");
        return null;
    }

}
public class ScheduledExecution {
    public static void main(String[] args) {
        ScheduledExecutorService sec = Executors.newScheduledThreadPool(10);
        sec.scheduleAtFixedRate(new ScheduledExecutionTest(), 5, 2, TimeUnit.SECONDS);
    }
}
FutureTask task1 = new FutureTask(Callable<V> callable)

现在这个 task1 是可运行的,因为:

  1. class FutureTask<V> implements RunnableFuture<V>
  2. RunnableFuture<V> extends Runnable, Future<V>

所以从以上两个关系来看,task1 是可运行的,可以在Executor.execute(Runnable)方法中使用

假设您真的不需要Callable返回任何有用的东西,您可以将 Callable 包装为 Runnable

Runnable run = new Runnable() {
    public void run() {
        try {
            Object o = callable.call();
            System.out.println("Returned " + o);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
};

或在 Java 8 中

Runnable run = () -> {
    try {
        Object o = callable.call();
        System.out.println("Returned " + o);
    } catch (Exception e) {
        e.printStackTrace();
    }
};

这很混乱,但听起来 Callable 一开始就应该是一个 Runnable 并且您不必这样做。

JDK 有一个 util 方法来解决这个问题:

Runnable runnable = ..
Executors.callable(runnable);

为什么不使用类似的东西:

  final Callable<YourType> callable = ...; // Initialize Callable

  Runnable callableAsRunnable = () -> {
     try {
        callable.call();
     } catch (Exception e) {
        // Handle the exception locally or throw a RuntimeException
     }
  };

使用 future task ,它实现了 Runnable 和 callable ,您不需要太多更改代码。

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/FutureTask.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM