Executors的四种线程池

Executors.newCachedThreadPool();
Executors.newFixedThreadPool(2);
Executors.newScheduledThreadPool(2);
Executors.newSingleThreadExecutor();

推荐使用ThreadPoolExecutor创建!

Executors.newCachedThreadPool()

public class MyRunnable implements Runnable {

    @Override
    public void run() {
        System.out.println("thread name is:" + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {
            MyRunnable myRunnable = new MyRunnable();
            threadPool.execute(myRunnable);
        }
        threadPool.shutdown();
    }
}

有的始终重复利用一条线程,因为newCachedThreadPool能重用可用线程。

thread name is:pool-1-thread-1
thread name is:pool-1-thread-2
thread name is:pool-1-thread-2
thread name is:pool-1-thread-1
thread name is:pool-1-thread-1

猜你喜欢

转载自www.cnblogs.com/bobi1234/p/10747452.html