【发布时间】:2017-11-09 20:42:16
【问题描述】:
在实现 Runnable 的名为 ExportShipmentThread 的单独类中的 Run 方法:
public void run() {
for (Shipment s : shipmentList) {
System.out.println("hi " + s.getId() + " Thread name " + Thread.currentThread().getName());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
主要在单独的类中:
int numberOfThreads = Integer.parseInt(reader.readLine());
ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
for(int i=0;i<10;i++){
ExportShipmentThread command = new ExportShipmentThread(shipmentList);
executorService.execute(command);
}
executorService.shutdown();
结果:
复制了前几条记录,
hi 2390900 Thread name pool-1-thread-1
hi 2390900 Thread name pool-1-thread-3
hi 2390900 Thread name pool-1-thread-2
hi 2390900 Thread name pool-1-thread-4
hi 2391990 Thread name pool-1-thread-1
hi 2391990 Thread name pool-1-thread-4
hi 2391990 Thread name pool-1-thread-2
hi 2391990 Thread name pool-1-thread-3
这里再次处理相同的数据,例如 2390900 被不同的线程重复,我希望输出没有重复,但由池中的不同线程处理。请指教。
【问题讨论】:
-
这不是预期的吗?您要求线程休眠 5 秒,下一个线程开始执行并从 shippinglist 中获取第一个元素。
-
如果您只想让列出的线程名称相同,您可以使用线程工厂,为所有创建的线程设置相同的名称。
标签: java multithreading threadpool