我们有一个大型文本文件,其中每行都需要进行密集的处理。设计方案是拥有一个类来读取文件,并将每一行的处理委派给线程池中的线程。当没有空闲线程来处理时,文件读取器类应该被阻塞,不能读取下一行。因此,我需要一个“阻塞式线程池”。
在当前实现中,ThreadPoolExecutor.submit()和ThreadPoolExecutor.execute()方法在配置的线程数达到上限后会抛出RejectedExecutionException异常,如下面的代码片段所示。
以上程序的输出结果是:
在当前实现中,ThreadPoolExecutor.submit()和ThreadPoolExecutor.execute()方法在配置的线程数达到上限后会抛出RejectedExecutionException异常,如下面的代码片段所示。
public class BlockingTp {
public static void main(String[] args) {
BlockingQueue blockingQueue = new ArrayBlockingQueue(3);
ThreadPoolExecutor executorService=
new ThreadPoolExecutor(1, 3, 30, TimeUnit.SECONDS, blockingQueue);
int Jobs = 10;
System.out.println("Starting application with " + Jobs + " jobs");
for (int i = 1; i <= Jobs; i++)
try {
executorService.submit(new WorkerThread(i));
System.out.println("job added " + (i));
} catch (RejectedExecutionException e) {
System.err.println("RejectedExecutionException");
}
}
}
class WorkerThread implements Runnable {
int job;
public WorkerThread(int job) {
this.job = job;
}
public void run() {
try {
Thread.sleep(1000);
} catch (Exception excep) {
}
}
}
以上程序的输出结果是:
Starting application to add 10 jobs
Added job #1
Added job #2
Added job #3
Added job #4
Added job #5
Added job #6
RejectedExecutionException
RejectedExecutionException
RejectedExecutionException
RejectedExecutionException
有人能够解释一下如何实现阻塞线程池吗?