【问题标题】:How to use multithreading/concurrency in my Java code如何在我的 Java 代码中使用多线程/并发
【发布时间】:2012-07-26 20:49:57
【问题描述】:

这是我的代码的简化:

for(int i = 0; i < 500; i++) {
    someMethod(i);
}

someMethod()执行时间长,所以想用多线程将for循环分解为5个100的区间:

for(int i = 0; i < 100; i++) {
    someMethod(i);
}

for(int i = 100; i < 200; i++) {
    someMethod(i);
}

...

for(int i = 400; i < 500; i++) {
    someMethod(i);
}

所以我可以同时为不同的i 执行someMethod()

如何使用多线程来完成此任务?

请帮忙!谢谢!

【问题讨论】:

  • 使用 ExecutorServices 和线程池
  • 小型且非常基本的示例here

标签: java multithreading


【解决方案1】:

建议在这种情况下使用出色的ExecutorService 代码。您所做的就是将所有任务(0 到 499)提交到线程池中,它们将由池中的 5 个线程并发运行。

类似于以下内容:

// create a thread pool with 5 workers
ExecutorService threadPool = Executors.newFixedThreadPool(5);
// submit all of your jobs here
for (int i = 0; i < 500; i++) {
    threadPool.submit(new MyJob(i));
}
// once we have submitted all jobs to the thread pool, it should be shutdown
threadPool.shutdown();
// if you need to wait for the pool you can do
threadPool.awaitTerminatation(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

private static class MyJob implements Runnable {
   private int i;
   public MyJob(int i) {
       this.i = i;
   }
   public void run() {
       // do the thread stuff here
   }
}

【讨论】:

  • // do the thread stuff here,你是什么意思?另外,someMethod() 是在哪里考虑到这一点的?
  • 所以@Jessica,您可以复制someMethod() 中的内容并将该代码放入run()。您还可以将派生线程的类传入MyJob 构造函数,然后在运行内部执行:caller.someMethod(i)。您的选择。
  • 只需将// do the thread stuff here 替换为someMethod(i); :) .. +1 为 Gray
  • 还有一个问题,如果有人还在的话:我的代码开头有一个boolean done = false。其中一个i 值将切换done。发生这种情况时,我想停止 for 循环。现在我将if(done) return;添加到run(),但是所有已经开始的someMethod()s都需要return;,所以会有很短的时间延迟。有什么更好的方法来做到这一点?
  • 这更难,因为作业已经提交到线程池。您可以使done 变得易变,只需将if (done) return; 放在run() 方法@Jessica 中的第一件事。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-19
  • 2017-02-22
  • 2012-11-06
  • 1970-01-01
  • 1970-01-01
  • 2021-09-22
  • 1970-01-01
相关资源
最近更新 更多