Callable实现多线程

时间:2021-04-18 21:44:09   收藏:0   阅读:19

Callable实现多线程

和Thread,Runnable实现多线程的区别

示例

import java.util.concurrent.*;

public class CallableExample01 implements Callable<Boolean> {

    //执行体
    public Boolean call() throws Exception {
        System.out.println("执行的线程为:" + Thread.currentThread().getName());
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CallableExample01 c1 = new CallableExample01();
        CallableExample01 c2 = new CallableExample01();
        CallableExample01 c3 = new CallableExample01();
        //1 创建执行服务
        ExecutorService ser = Executors.newFixedThreadPool(3);
        //2 提交执行
        Future<Boolean> f1 = ser.submit(c1);
        Future<Boolean> f2 = ser.submit(c2);
        Future<Boolean> f3 = ser.submit(c3);
        //3 获取结果
        boolean res = f1.get();
        boolean res1 = f2.get();
        boolean res2 = f3.get();
        //4 关闭服务
        ser.shutdownNow();
    }

执行结果

执行的线程为:pool-1-thread-1
执行的线程为:pool-1-thread-2
执行的线程为:pool-1-thread-3

原文:https://www.cnblogs.com/lanxinren/p/14674550.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!