【问题标题】:How do I implement thread pool for the single task need to be handled by multiple threads?如何为需要由多个线程处理的单个任务实现线程池?
【发布时间】: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


【解决方案1】:

您的主题应该只适用于一个 Shipment 而不是所有的。然后对于列表中的每个货件,使用该货件运行一个线程。

【讨论】:

    猜你喜欢
    • 2012-09-03
    • 1970-01-01
    • 1970-01-01
    • 2012-03-31
    • 2012-02-12
    • 1970-01-01
    • 2012-12-05
    • 2015-04-24
    • 2012-03-23
    相关资源
    最近更新 更多