简体   繁体   中英

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:

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 .

How do I use multithreading to accomplish this?

Please help! Thanks!

It is recommended to use the great ExecutorService code for situations like this. 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.

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
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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