线程池多线程处理多任务,适用按顺序输出结果


	线程池多线程处理多任务,适用按顺序输出结果
[编程语言教程]

package com.test;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;

public class ThreadPoolExecutorTest2 {
    public static void main(String[] args)  throws InterruptedException, ExecutionException{
        ThreadPoolExecutorTest2 threadPoolExecutorTest2 = new ThreadPoolExecutorTest2();
        threadPoolExecutorTest2.doThing();
    }

    public void doThing() throws InterruptedException, ExecutionException {
        /**
         * 创建线程池,并发量最大为5
         * LinkedBlockingDeque,表示执行任务或者放入队列
         */
        ThreadPoolExecutor tpe = new ThreadPoolExecutor(5, 10, 0,
                TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(),
                new ThreadPoolExecutor.CallerRunsPolicy());

        //存储线程的返回值
        List<Future<String>> results = new LinkedList<Future<String>>();

        for (int i = 0; i < 10; i++) {
            Task task = new Task(i);
            System.out.println("放入线程池:" + i);
            //调用submit可以获得线程的返回值
            Future<String> result = tpe.submit(task);
            results.add(result);

        }

        //此函数表示不再接收新任务,
        //如果不调用,awaitTermination将一直阻塞
        tpe.shutdown();
        //1小时,模拟等待
        System.out.println(tpe.awaitTermination(1, TimeUnit.HOURS));

        //输出结果
        for (int i = 0; i < 10; i++) {
            System.out.println(results.get(i).get());
        }
    }


    private class Task implements Callable {
        private int val;

        public Task(int val) {
            this.val = val;
        }

        @Override
        public String call() throws Exception {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("完成 "+ val);
            return "返回值" + val;
        }
    }
}
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » 线程池多线程处理多任务,适用按顺序输出结果