简体   繁体   English

如何在我的Java代码中使用多线程/并发

[英]How to use multithreading/concurrency in my Java code

This is a simplification of my code: 这是我的代码的简化:

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

someMethod() takes a long time to execute, so I want to use multithreading to break up the for-loop into 5 intervals of 100: 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);
}

so I can execute someMethod() concurrently for different i . 所以我可以为不同的i同时执行someMethod()

How do I use multithreading to accomplish this? 如何使用多线程来完成此任务?

Please help! 请帮忙! Thanks! 谢谢!

It is recommended to use the great ExecutorService code for situations like this. 对于这种情况,建议使用出色的ExecutorService代码。 What you do is submit all of your tasks (0 to 499) into the thread pool and they will be run concurrently by the 5 threads in the pool. 您要做的是将所有任务(0到499)提交到线程池中,它们将由池中的5个线程同时运行。

Something like the following: 类似于以下内容:

// 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM