码迷,mamicode.com
首页 > 编程语言 > 详细

自定义的最简单的可回调的线程任务CallbackableFeatureTask(模仿google的ListenableFutureTask)

时间:2019-10-23 13:23:17      阅读:325      评论:0      收藏:0      [点我收藏+]

标签:code   exec   override   sub   static   str   cat   callback   rri   

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)

标签:code   exec   override   sub   static   str   cat   callback   rri   

原文地址:https://www.cnblogs.com/zhshlimi/p/11725614.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!