在名为ExportShipmentThread的单独类中运行方法,该类实现Runnable:
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
由不同的线程重复一样,我希望输出没有重复,但是由池中的不同线程处理。请指教。
答案 0 :(得分:0)
您的主题应仅适用于货件而非全部货件。然后,对于列表中的每个货件,运行一个包含货件的线程。