package com.jiading.pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class singleThreadTest {
public static void main(String[] args) {
/**
* JAVA通過Executors提供了四種線程池,newSingleThreadExecutor創建的單線程線程池是其一
* 單線程化的線程池
* 那你如果要問單線程了為什么還要用線程池,只能是在一般情況下它是和單線程沒區別的,但是如果這個唯一的線程因為異常結束,那么會有一個新的線程來替代它。
* 這一點是單線程沒辦法做到的
* 單線程線程池corePoolSize和maximumPoolSize都是1。所以絕對只有一個線程在執行,如果等待隊列滿了就直接拒絕執行新任務
* 單線程線程池和定長線程池的阻塞隊列使用的偶數LinkedBlockingQueue,默認的大小是int的最大值
*/
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
for(int i = 0;i < 10;i++) {
final int index = i;//給變量加個final挺好,省的它變
singleThreadExecutor.execute(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("Thread i = " + index);
System.out.println(Thread.currentThread().getName() + " index = " + index);
try {
Thread.sleep(500);
System.out.println("sleep finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
singleThreadExecutor.shutdown();
System.out.println("on the main thread...");
}
}
輸出為:
on the main thread...
Thread i = 0 index = 0
sleep finished
Thread i = 1 index = 1
sleep finished
Thread i = 2 index = 2
sleep finished
Thread i = 3 index = 3
sleep finished
Thread i = 4 index = 4
sleep finished
Thread i = 5 index = 5
sleep finished
Thread i = 6 index = 6
sleep finished
Thread i = 7 index = 7
sleep finished
Thread i = 8 index = 8
sleep finished
Thread i = 9 index = 9
sleep finished
從輸出也能看出來是只有一個線程了,sleep之后再喚醒。只要沒有異常,一直是這一個