Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of threads?

So I am having an issue understanding how to avoid sequential execution of threads. I am attempting to create an array of threads and execute the start() and join() functions in separate loops. Here's a code example of what I have now:

    private static int[] w;

static class wThreads implements Runnable {

        private final int i;

        public wThreads(int i) {
            this.i = i;
        }

        //Set member values to 1
        @Override
        public void run() {
            //doing specific stuff here
        }
    }

And here's where the threads are created in main:

int argSize = Integer.parseInt(args[0]);

    w = new int[argSize];

    //Initialize w
    for (int i = 0; i < argSize; i++) {
        wThreads wt = new wThreads(i);
        for (int j = 0; j < argSize - 1; j++) {
            Thread t = new Thread(wt);
            t.start();
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

So apparently this is not an example of threads working in parallel. They are waiting for each other to finish. I know that the join() and start() calls should be in different loops, but how can I reference the thread in a different loop than the one it's initially created in?

Do I need to create an array of threads in the class declaration? Should the loops be in there as well, and outside of main?

I'm quite confused and any info would be appreciated. Thank you!

like image 544
Syrne Avatar asked Oct 24 '14 01:10

Syrne


1 Answers

You can't do the join inside the loop where you are starting them (you can but as you have found, there is no parallelism). Create an array for the threads, start them in one loop and then create a second loop that does the join call. I don't think you want the inner for at all.

Thread myThreads[] = new Thread[argsize];
for (int j = 0; j < argSize; j++) {
    myThreads[j] = new Thread(new wThreads(j));
    myThreads[j].start();
}
for (int j = 0; j < argSize; j++) {
    myThreads[j].join(); //todo add catch exception
}

I suspect you want to do this yourself, but the standard way is using Executor, Thread Pools and such, see Oracle Tutorials

like image 159
Dylan Avatar answered Sep 30 '22 14:09

Dylan