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
上一篇:知识点查缺补漏贴02:Linux环境fork()函数详解


下一篇:SSH Secure Shell Client的傻瓜式使用方法