【问题标题】:how to apply a multi threading to process List<MyDto> 5 dto objects at atime如何应用多线程一次处理 List<Dto> 5 个 dto 对象
【发布时间】:2016-12-04 20:56:23
【问题描述】:

下面的场景需要不同的想法,假设从Statementexecute()方法得到一个ResultSet对象,这个ResultSet对象可能包含数千条记录,这里我更新每个ResultSet对象的数据到 DTO 对象中。

得到了List&lt;MyDTO&gt; myDTOList,现在我想在一个线程中处理每个 DTO,一次最多处理 5 个线程,即 5 个 DTO 对象。

(剩余的 DTO 应该等待完成至少一个线程执行,如果一个线程完成它的工作想要添加另一个线程,所以它又是 5 个线程正在运行.. 所以进程将继续所有 DTO 对象)

有哪些可用的方法来实现这种要求?

提前感谢您的时间和建议。

【问题讨论】:

  • 这有点像atm机器的实时场景,里面有5台atm机器,但数百名用户正在等待访问它。但一次只有 5 个可以访问。

标签: java multithreading threadpool executorservice threadpoolexecutor


【解决方案1】:

使用

public class YourTask implements Callable<String> {

//Ctor
YourTask(data) {
   // save data in member variables
}

public String call() throws Exception {
    // Process data
    // return string

}

}

ExecutorService threadPool = Executors.newFixedThreadPool(5); 
List<java.util.concurrent.Future<String>> futures = new ArrayList<Future<String>>();


for (your data) {
    futures.add(threadPool.submit(new YourTask(pass_data)));
}

// Wait for threads to finish i.e. join them
for (Future<String> f :futures){
        try {
            String c = f.get();
            doneCount++;

        } catch (InterruptedException e) {
            //
        } catch (ExecutionException e) {
            //
        }
            }

【讨论】:

  • 完美.. 谢谢.. 完成所有线程后,控制器没有从程序中出来,需要为此添加任何东西吗?
  • if(doneCount == testDTOList.size()){ System.out.println("完成所有线程..."); System.exit(0); }
  • 将其保留在 for 循环中,停止控制器可以吗?
  • 您的控制器将卡在for (futures) 循环中,直到所有线程完成,然后 doneCount 将等于您的 DTO 大小。
  • 不客气。有机会请采纳答案。
【解决方案2】:

带有固定线程池的ExecutorService专为此类任务设计:

// Task that will process DTOs
public class DTOTask implements Callable<Void> {
    private MyDTO obj;

    public DTOTask(MyDTO obj) {
        this.obj = obj;
    }

    @Override
    public Void call() {
        // Process obj here
    };
}

ExecutorService executor = Executors.newFixedThreadPool(5);

Future<?> future = executor.submit(new DTOTask(myDObject));

您可以使用futures 来取消任务、等待其完成、检索结果和做其他事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 2017-12-08
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多