简体   繁体   中英

Multiplle Threads in Java

I have a loop for example for (int i=1;i<=10;i++) and I want to create 10 threads inside it, each one to perform the same task on a set of data and return the result. Then process this result inside the loop. Any ideas how this can be done?

for (int i=1;i<=10;i++) {
    Work w = new Work();
    Thread t = new Thread(w);
    w.getResultFromThread();
    //process w
}

class Work implements Runnable {
     public void run() {
      //perform tasks
     }

     public int getResultFromThread() {
          return result;
     }
}

I want each thread to work in parallel but when I recieve the result to be one by one.

If you do not wish to use executors, the you can do it in the following way:

int size = 10;
Thread[] threads = new Thread[size];
Work[] works = new Work[size];
for (int i = 1; i <= size; i++) {

    Work w = new Work();
    works[i - 1] = w;
    Thread t = new Thread(w);
    threads[i - 1] = t;

    // Start the thread
    t.start();
}
// now you have started all the threads


for (int i = 0; i < size; i++) {

    // wait for each thread to complete execution, before extracting the result
    // [here i am assuming that getResultFromThread() does not block
    // till we get the result, if it blocks, then no need to join]
    threads[i].join();

    int result = works[i].getResultFromThread();
    // do something with the result
}
ArrayList<Work> listOfJobs = new ArrayList<Work>();
ArrayList<Thread> threadList = new ArrayList<Thread>();
for(int i = 0 ; i < 10; i++) {
  Work w = new Work();
  listOfJobs.add(w);
  Thread t = new Thread(w);
  threadList.add(t);
  t.start();
}

for(Thread t : listOfJobs) {
    t.join();
    w.getResultsFromThread();
}

This way you don't need executors for whatever reason you might have not to use them.

First, you create all the threads and start them(1st loop), then you call join on them, to make sure thread you want to get results from is done(2nd loop).

You can always pass your listOfJobs to some other method to process your results.

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