多线程(13)线程池2

一:线程池

有四种创建线程池方法,但是我们开发是不推荐使用的,我们可以直接自己创建线程池,来配置我们需要的参数来实现

Executors.newCachedThreadPool();
Executors.newFixedThreadPool(5);
Executors.newSingleThreadExecutor();
Executors.newScheduledThreadPool(3);
public class Test {
    public static void main(String[] args) {
        ExecutorService service= Executors.newCachedThreadPool();
        ThreadPoolExecutor threads=new ThreadPoolExecutor(2,3,8, TimeUnit.SECONDS,new ArrayBlockingQueue<>(5));
        for(int i=0;i<100;i++) {
            threads.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName());
            }
               // execute和submit的区别:
               // execute只能提交Runnable类型的任务,无返回值。submit既可以提交Runnable类型的任务,也可以提交Callable类型的任务,会有一个类型为Future的返回值,但当任务类型为Runnable时,返回值为null。
               // execute在执行任务时,如果遇到异常会直接抛出,而submit不会直接抛出,只有在使用Future的get方法获取返回值时,才会抛出异常
        });
        }
    }
}

 执行多个任务:Callable返回结果

public class Test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService service= Executors.newCachedThreadPool();
        //创建线程池
        ThreadPoolExecutor threads=new ThreadPoolExecutor(2,3,8, TimeUnit.SECONDS,new ArrayBlockingQueue<>(5));
        ArrayList<Object> sum=new ArrayList<>();
        for (int i = 0; i <10; i++) {
            //相当于提交了多个线程,for循环就是我们提交多个线程来执行******
            Future<Object> future = threads.submit(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    int j = 0;
                    j++;
                    Thread.sleep(50);
                    System.out.println(Thread.currentThread().getName());
                    return j;
                }
            });
            sum.add(future.get());
        }
        System.out.println(sum.toString());
}
}

pool-2-thread-1
pool-2-thread-2
pool-2-thread-1
pool-2-thread-2
pool-2-thread-1
pool-2-thread-2
pool-2-thread-1
pool-2-thread-2
pool-2-thread-1
pool-2-thread-2
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

  

posted @ 2022-03-08 14:35  iLisa  阅读(24)  评论(0编辑  收藏  举报