线程池ThreadPoolExecutor配合callable获得线程执行结果

此处记录使用callable创建线程,使用线程池执行,看下是否有进行线程复用并且FutureTask返回结果

线程创建

public class MyCallableBakeUser implements Callable<String> {

    private int a ;

    public MyCallableBakeUser(int a){
        this.a = a;
    }


    @Override
    public String call() throws Exception {

        int sum = 0;

        for (int i = 0; i < a; i++) {
            sum += i;
        }

        return Thread.currentThread().getName() + " 线程求和:" + sum;
    }
}

使用main测试

public class ThreadCallPool {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(3,5,8,
                TimeUnit.SECONDS,new ArrayBlockingQueue<>(4),
                Executors.defaultThreadFactory(),new ThreadPoolExecutor.CallerRunsPolicy());
        Future<String> future = poolExecutor.submit(new MyCallableBakeUser(10));
        Future<String> future1 = poolExecutor.submit(new MyCallableBakeUser(20));
        Future<String> future2 = poolExecutor.submit(new MyCallableBakeUser(30));
        Future<String> future3 = poolExecutor.submit(new MyCallableBakeUser(40));
        System.out.println(future.get());
        System.out.println(future1.get());
        System.out.println(future2.get());
        System.out.println(future3.get());


    }

}

控制台打印:

pool-1-thread-1 线程求和:45
pool-1-thread-2 线程求和:190
pool-1-thread-3 线程求和:435
pool-1-thread-1 线程求和:780

核心线程数为3个,说明线程得到复用,同时也得到callable的返回值

 

以上内容纯属学习!

 

posted @ 2024-10-31 16:59  多多指教~  阅读(13)  评论(0编辑  收藏  举报