[英]How to use multithreading/concurrency in my Java code
这是我的代码的简化:
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()
。
如何使用多线程来完成此任务?
请帮忙! 谢谢!
对于这种情况,建议使用出色的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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.