Java创建线程池的三种方法

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThreadDemo {
    public static void main(String[] args) throws InterruptedException {

        ExecutorService threadPool1 = Executors.newSingleThreadExecutor();// 单个线程池
        ExecutorService threadPool2 = Executors.newFixedThreadPool(6);// 固定线程池
        ExecutorService threadPool3 = Executors.newCachedThreadPool();// 可大可小线程池(线程池大小不固定)
        for (int i = 1; i < 10; i++) {
            threadPool1.execute(() -> {
                System.out.println("Single当前线程池名称:" + Thread.currentThread().getName());
            });
        }
        TimeUnit.SECONDS.sleep(5);
        System.out.println("===================================================");

        for (int i = 1; i < 10; i++) {
            threadPool2.execute(() -> {
                System.out.println("Fixed当前线程池名称:" + Thread.currentThread().getName());
            });
        }
        TimeUnit.SECONDS.sleep(5);
        System.out.println("===================================================");

        for (int i = 1; i < 10; i++) {
            threadPool3.execute(() -> {
                System.out.println("Cached当前线程池名称:" + Thread.currentThread().getName());
            });
        }
    }
}

 

posted @ 2021-12-29 16:00  蛋挞小子  阅读(226)  评论(0编辑  收藏  举报