java.util.concurrent.Executors为我们提供了多种构造线程池的方法,可以构造多种类型的线程池对象,可以满足多种业务需求。
但是并没有提供一个可以阻塞放入的线程池,业务场景描述如下:
我们有个任务表,任务会自动增加。我们需要多线程来处理任务表的任务,主线程一次取出50个任务,然后放入线程池处理,如果使用普通的线程池,取出任务马上就放进了线程池队列,如果任务过多,可能会导致内存溢出(无界队列的情况);也可能被拒绝处理或立即处理(有界队列,队列满后触发了拒绝策略);那么这时候我们考虑:如果线程池已满,主线程阻塞, 不要在取数据了,等待线程池有空闲时,自动再取,这样岂不完美。所以我们需要可以阻塞放入的线程池。
具体实现如下:
public class BlockThreadPool {
private ExecutorService threadPool = null;
public BlockThreadPool(int poolSize) {
threadPool = new ThreadPoolExecutor(
poolSize,
poolSize,
0,
TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(5), // 有界队列
new CustThreadFactory(),
new CustRejectedExecutionHandler() //拒绝策略
);
}
private class CustThreadFactory implements ThreadFactory {
private AtomicInteger count = new AtomicInteger(0);
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
String threadName = BlockThreadPool.class.getSimpleName() + count.addAndGet(1);
t.setName(threadName);
return t;
}
}
private class CustRejectedExecutionHandler implements RejectedExecutionHandler {
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
executor.getQueue().put(r);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void execute(Runnable runnable) {
this.threadPool.execute(runnable);
}
public static void main(String[] args) {
BlockThreadPool blockThreadPool=new BlockThreadPool(5);
for (int i = 0; i < 100; i++) {
blockThreadPool.execute(new Runnable() {
public void run() {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getId());
}
});
System.out.println("放入第"+i+"个任务成功");
}
}
}