自定义的最简单的可回调的线程任务CallbackableFeatureTask(模仿google的ListenableFutureTask)
Posted zhshlimi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义的最简单的可回调的线程任务CallbackableFeatureTask(模仿google的ListenableFutureTask)相关的知识,希望对你有一定的参考价值。
1.使该Task继承Callable,Runable
import java.util.concurrent.Callable; import java.util.function.Consumer; public class CallbackableFeatureTask<V> implements Callable<V>, Runnable { private Callable<V> mainProcess; private Consumer<V> callbackFunction; @Override public V call() throws Exception { V result = mainProcess.call(); callbackFunction.accept(result); return result; } public CallbackableFeatureTask(Callable<V> callable, Consumer<V> callbackFunction) { this.mainProcess = callable; this.callbackFunction = callbackFunction; } @Override public void run() { try { call(); } catch (Exception ex) { } } }
2.测试代码
public class CallbackableFeatureTaskTest { private static ExecutorService executorService = Executors.newFixedThreadPool(5); public static void main(String[] args) { CallbackableFeatureTask<String> task = new CallbackableFeatureTask<>(new Callable<String>() { @Override public String call() throws Exception { return "Hello China!"; } }, (String v) -> { System.out.println(v); }); // 1.支持直接使用线程的Runnable new Thread(task).start(); //2.支持使用线程池的Callable Future<String> result = executorService.submit((Callable<String>) task); try { System.out.println("使用线程池返回结果是:" + result.get()); } catch (Exception ex) { }
executorService.shutdown();
}
}
结果如下:
Hello China!
Hello China!
使用线程池返回结果是:Hello China!
这里仅仅做一个教学Demo
后期可以优化的点: 实现Future<V>接口,继承FutureTask 类等
以上是关于自定义的最简单的可回调的线程任务CallbackableFeatureTask(模仿google的ListenableFutureTask)的主要内容,如果未能解决你的问题,请参考以下文章