自定义线程池(单例模式)
package com.example.demo.ThreadPool;
import java.util.concurrent.*;
public class SyncGlobalThreadPool {
private static class SingletonHolder {
private static ExecutorService threadPool = new ThreadPoolExecutor(
5,
5,
30,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(20),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy()
);
}
public SyncGlobalThreadPool() {
}
public static ExecutorService getInstance() {
return SingletonHolder.threadPool;
}
}
使用线程池异步处理任务
- 定义线程类 BuildFileThread,执行业务逻辑。需要传入CountDownLatch
- 使用CountDownLatch 等待所有线程执行完,再继续执行主线程
package com.example.demo.ThreadPool;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
public class test {
public void x() {
ExecutorService executorService = SyncGlobalThreadPool.getInstance();
List<Long> ids = Arrays.asList(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L);
long t1 = System.currentTimeMillis();
CountDownLatch c=new CountDownLatch(ids.size());
Iterator<Long> it = ids.iterator();
while (it.hasNext()) {
executorService.submit(new BuildFileThread(it.next(),c));
}
try {
c.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
long t2 = System.currentTimeMillis();
System.out.println("执行时间:" + (t2 - t1) / 1000+"s");
executorService.shutdown();
}
class BuildFileThread implements Runnable {
long id;
CountDownLatch c;
public BuildFileThread(long id, CountDownLatch c) {
this.id = id;
this.c = c;
}
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("id=" + id + " 线程" + Thread.currentThread().getName());
c.countDown();
}
}
}