[英]run method in thread pool
I little bit out of understanding java.util.concurent package, all those services and executors. 我有点不了解java.util.concurent包,所有这些服务和执行程序。
I need a quite simple thing - let say I have 我需要一件很简单的事情-假设我有
for( int i=0;i<1000;i++){
doSomething(i); //all tasks are run 10ms and does not lock each other
}
What is the easiest way to convert this code to run by group of 10 threads. 将此代码转换为由10个线程组运行的最简单方法是什么。
If possible can I re-use proposed solution for another group of tasks(not wrapping each time in run())? 如果可能,我是否可以将提议的解决方案重新用于另一组任务(不是每次都在run()中包装)?
Here is what you need : 这是您需要的:
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 1000; i++) {
Runnable worker = new doSomething(i);
executor.execute(worker);
}
executor.shutdown();
and your doSomething class will be like this : 和您的doSomething类将是这样的:
class doSomething implements Runnable {
int i=0;
doSomething(int i) {
this.i = i;
}
@Override
public void run() {
try {
// Do what you want here
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Edited : ExecutorService#shutdown()
initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. 编辑 :
ExecutorService#shutdown()
启动有序关闭,在该关闭中将执行先前提交的任务,但不会接受任何新任务。 Invocation has no additional effect if already shut down. 如果已关闭,则调用不会产生任何其他影响。 This method does not wait for previously submitted tasks to complete execution.
此方法不等待先前提交的任务完成执行。 Use awaitTermination to do that.
使用awaitTermination可以做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.