Java线程池(java.util.concurrent.ThreadPoolExecutor
)实现了接口java.util.concurrent.ExecutorService
,将线程资源缓存起来,实现了线程的复用。
package bj;
import io.vavr.control.Try;
import java.time.LocalTime;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.IntStream;
/**
* Created by BaiJiFeiLong@gmail.com at 2018/12/7 上午10:05
*/
public class FooTest {
public static void main(String[] args) {
ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 6, 5, TimeUnit.SECONDS, new LinkedBlockingQueue<>(3), new ThreadFactory() {
private int count = 0;
@Override
public Thread newThread(Runnable r) {
return new Thread(r, String.format("Thread[%d]", ++count));
}
}, (r, executor1) -> System.out.println("Ignored: " + r));
executor.allowCoreThreadTimeOut(true);
IntStream.range(0, 10).forEach($ -> executor.execute(() -> {
Try.run(() -> Thread.sleep(1000)).getOrElseThrow((Supplier<RuntimeException>) RuntimeException::new);
System.out.println(String.format("%s Progress: %d Thread: %s", LocalTime.now(), $, Thread.currentThread().getName()));
}));
}
}
Ignored: bj.FooTest$$Lambda$3/783286238@27082746
14:13:53.247 Progress: 0 Thread: Thread[1]
14:13:53.247 Progress: 2 Thread: Thread[3]
14:13:53.247 Progress: 8 Thread: Thread[6]
14:13:53.247 Progress: 3 Thread: Thread[4]
14:13:53.248 Progress: 1 Thread: Thread[2]
14:13:53.248 Progress: 7 Thread: Thread[5]
14:13:54.252 Progress: 5 Thread: Thread[6]
14:13:54.252 Progress: 6 Thread: Thread[3]
14:13:54.252 Progress: 4 Thread: Thread[1]
Process finished with exit code 0
以线程池参数最多的构造函数(java.util.concurrent.ThreadPoolExecutor#ThreadPoolExecutor(int, int, long, java.util.concurrent.TimeUnit, java.util.concurrent.BlockingQueue<java.lang.Runnable>, java.util.concurrent.ThreadFactory, java.util.concurrent.RejectedExecutionHandler)
)为例
allowCoreThreadTimeOut
设为true
,核心池中的线程超时后自动销毁线程池的存在,默认会阻止主程序的自动退出。销毁掉线程池中的全部线程后,主程序才可以顺利退出。
实现线程池任务全部接触后,自动销毁全部线程,有两种方式:
executor.allowCoreThreadTimeOut(true);
将核心池中的线程设为超时自动销毁executor.setCorePoolSize(0);
将核心池大小设为0,核心池中的线程执行完后会自动销毁