1. 程式人生 > >java執行緒池(newCachedThreadPool)的使用

java執行緒池(newCachedThreadPool)的使用


import java.util.concurrent.*;

/**
 * java執行緒池的使用 
 * 這個【可快取執行緒池】,沒看出來有什麼用呢。。。
 */
public class ExecutorServiceTest {
	public static void main(String[] args) throws ExecutionException, InterruptedException {

		ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
		for (int i = 0; i < 10; i++) {
			final int index = i;
			Thread.sleep(index * 1000);
			cachedThreadPool.execute(new Runnable() {
				@Override
				public void run() {
					System.out.println(index + " 當前執行緒:" + Thread.currentThread().getName() + "當前任務時間:"
							+ System.currentTimeMillis());
				}
			});
		}
	}
}

列印結果:

0 當前執行緒:pool-1-thread-1當前任務時間:1538209339519
1 當前執行緒:pool-1-thread-1當前任務時間:1538209340519
2 當前執行緒:pool-1-thread-1當前任務時間:1538209342519
3 當前執行緒:pool-1-thread-1當前任務時間:1538209345519
4 當前執行緒:pool-1-thread-1當前任務時間:1538209349519
5 當前執行緒:pool-1-thread-1當前任務時間:1538209354519
6 當前執行緒:pool-1-thread-1當前任務時間:1538209360519
7 當前執行緒:pool-1-thread-1當前任務時間:1538209367519
8 當前執行緒:pool-1-thread-1當前任務時間:1538209375519
9 當前執行緒:pool-1-thread-1當前任務時間:1538209384519

執行緒池為無限大,當執行第二個任務時第一個任務已經完成,會複用執行第一個任務的執行緒,而不用每次新建執行緒。所以任務太多,可能系統會癱瘓。