ThreadFactory是一個接口,只有一個用來創(chuàng)建線程的方法:
Thread newThread(Runnable r);
當(dāng)線程池中需要創(chuàng)建線程時就會調(diào)用該方法。
package com.wkcto.threadpool;
import java.util.Random;
import java.util.concurrent.*;
/**
* 自定義線程工廠
*/
public class Test04 {
public static void main(String[] args) throws InterruptedException {
//定義任務(wù)
Runnable r = new Runnable() {
@Override
public void run() {
int num = new Random().nextInt(10);
System.out.println(Thread.currentThread().getId() + "--" + System.currentTimeMillis() + "開始睡眠:" + num + "秒");
try {
TimeUnit.SECONDS.sleep(num);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
//創(chuàng)建線程池, 使用自定義線程工廠, 采用默認(rèn)的拒絕策略是拋出異常
ExecutorService executorService = new ThreadPoolExecutor(5, 5, 0, TimeUnit.SECONDS, new SynchronousQueue<>(), new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
//根據(jù)參數(shù)r接收的任務(wù),創(chuàng)建一個線程
Thread t = new Thread( r );
t.setDaemon(true); //設(shè)置為守護(hù)線程, 當(dāng)主線程運行結(jié)束,線程池中的線程會自動退出
System.out.println("創(chuàng)建了線程: " + t);
return t ;
}
});
//提交5個任務(wù), 當(dāng)給當(dāng)前線程池提交的任務(wù)超過5個時,線程池默認(rèn)拋出異常
for (int i = 0; i < 5; i++) {
executorService.submit(r);
}
//主線程睡眠
Thread.sleep(10000);
//主線程睡眠超時, 主線程結(jié)束, 線程池中的線程會自動退出
}
}