1. 程式人生 > >Executors的四種線程池

Executors的四種線程池

ews sin 重復 ice code 線程 pool single string

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

Executors的四種線程池