Java5中线程池与线程结果返回

Exectutors

//以下为各种起线程池方式

        //ExecutorService threadPool = Executors.newFixedThreadPool(3);
        //ExecutorService threadPool = Executors.newCachedThreadPool();
        // ExecutorService threadPool = Executors.newSingleThreadExecutor();

//等待6秒后间隔2秒就定时任务调起,       

Executors.newScheduledThreadPool(3).scheduleAtFixedRate(
                new Runnable(){
                    @Override
                public void run() {
                    System.out.println("bombing!");
                    
                }},
                6,
                2,
                TimeUnit.SECONDS);

/./起一个单例线程,线程死了会重新拉起来

        ExecutorService threadPool =  Executors.newSingleThreadExecutor();
        //通过Future对象可获取线程返回结果

        Future<String> future =
            threadPool.submit(
                new Callable<String>() {
                    public String call() throws Exception {
                        Thread.sleep(2000);
                        return "hello";
                    };
                }
        );

//等待线程返回结果打印出来

System.out.println(“thread return: ”+ future.get());

-------------------------------------------------------------

//创建一个10个纯种的线程池      

ExecutorService threadPool2 =  Executors.newFixedThreadPool(10);

//CompletionService可以获取先运行结束的线程返回
        CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2);

//提交10个任务
        for(int i=1;i<=10;i++){
            final int seq = i;
            completionService.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    Thread.sleep(new Random().nextInt(5000));
                    return seq;
                }
            });
        }

        //等待10个任务的线程返回结果(先运行完的为第一个返回)
        for(int i=0;i<10;i++){
            try {
                System.out.println(
                        completionService.take().get());
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值