列表提交给 ThreadPoolExecutor 和条件应该是每个线程选择长 LinkedBlockingQueue 并并行执行
这是我的方法逻辑
public void doParallelProcess() {
List<LinkedBlockingQueue<Long>> linkedBlockingQueueList = splitListtoBlockingQueues();
ThreadPoolExecutor executor = new ThreadPoolExecutor(1, linkedBlockingQueueList.size(), 0L,
TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), Executors.defaultThreadFactory());
Long initial = System.currentTimeMillis();
try {
System.out.println("linkedBlockingQueueList begin size is " + linkedBlockingQueueList.size() + "is empty"
+ linkedBlockingQueueList.isEmpty());
while (true) {
linkedBlockingQueueList.parallelStream().parallel().filter(q -> !q.isEmpty()).forEach(queue -> {
Long id = queue.poll();
MyTestRunnable runnab = new MyTestRunnable(id);
executor.execute(runnab);
System.out.println("Task Count: " + executor.getTaskCount() + ", Completed Task Count: "
+ executor.getCompletedTaskCount() + ", Active Task Count: " + executor.getActiveCount());
});
System.out.println("linkedBlockingQueueList end size is " + linkedBlockingQueueList.size() + "is empty"
+ linkedBlockingQueueList.isEmpty());
System.out.println("executor service " + executor);
if (executor.getCompletedTaskCount() == (long) mainList.size()) {
break;
}
while (executor.getActiveCount() != 0) {
System.out.println("Task Count: " + executor.getTaskCount() + ", Completed Task Count: "
+ executor.getCompletedTaskCount() + ", Active Task Count: " + executor.getActiveCount());
Thread.sleep(1000L);
}
}
} catch (Exception e) {
} finally {
executor.shutdown();
while (!executor.isTerminated()) {
}
}
} `
如何将 LinkedBlockingQueue 列表提交到单个线程例:
-
List<LinkedBlockingQueue<Long>>
每个链接阻塞队列包含 50 个队列数据 List<LinkedBlockingQueue<Long>>
的大小是 50- 每个线程应选择一个
LinkedBlockingQueue<Long>
并执行 50 个队列任务。
ExecutorService
的输入要么是Runnable
,要么是Callable
。您提交的任何任务都需要实现这两个接口之一。如果你想将一堆任务提交到线程池并等到它们全部完成,那么你可以使用 invokeAll 方法并循环生成的 Future
s,在每个 s 上调用 get
:请参阅这个对类似问题的信息性答案。
但是,您无需将输入任务批处理到组中。您永远不希望执行程序服务在仍有工作要做时具有空闲线程!您希望它能够在资源释放后立即抓取下一个任务,而以这种方式进行批处理与此相反。您的代码正在执行以下操作:
while non-empty input lists exist {
for each non-empty input list L {
t = new Runnable(L.pop())
executor.submit(t)
}
while (executor.hasTasks()) {
wait
}
}
一旦其中一个任务完成,该线程应该可以自由地继续其他工作。但它不会,因为您等到所有 N 个任务都完成后再提交。使用 invokeAll
一次提交所有内容,并让执行程序服务执行其构建目的。
Executors
类是线程池的主要条目:
ExecutorService executor = Executors.newCachedThreadPool();
linkedBlockingQueueList.forEach(queue -> executor.submit(() -> { /* process queue */ }));
如果您确实想自己创建一个ThreadPoolExecutor
(它确实可以让您更好地控制配置(,则至少有两种方法可以指定默认线程工厂:
省略线程工厂参数:
ThreadPoolExecutor executor = new ThreadPoolExecutor(1, linkedBlockingQueueList.size(), 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
再次使用
Executors
类获取默认线程工厂:ThreadPoolExecutor executor = new ThreadPoolExecutor(1, linkedBlockingQueueList.size(), 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), Executors.defaultThreadFactory());