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

Pul*_*kit 4 java multithreading callable runnable scheduledexecutorservice

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

因此我需要一些方法可以将callable转换为runnable.我试过简单的铸造,但那是行不通的.

示例代码:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 9

FutureTask task1 = new FutureTask(Callable<V> callable)
Run Code Online (Sandbox Code Playgroud)

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

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

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