Reputation: 350
Below is a class that I wrote where the intent was that we create different threads from the main program which run in parallel and the main thread resumes execution after all the threads have finished execution. The t.join in the code joins the next thread to the first thread. Say if there are 2 threads with the random number generator generating 8 and 9 as integers then the main thread resumes after 17 seconds. The intent was to create threads in parallel such that the main thread resumes after the 9th second (the first thread runs completely in the first 8 seconds and then the second thread finishes execution in the next 1 second). Is it possible to create such a code by making a change to the below code?
I solved it by using a static variable which gets incremented by each thread after execution and when the thread count reaches a certain threshold we stop the execution. But is there any other way to do this ?
import java.util.Random;
public class ThreadsPlay {
public static void main(String[] args) {
try
{
for(int i=3;i<12;i=i+3)
{
Thread t=new Thread(){
Random r=new Random();
int count=r.nextInt(10);
public void run()
{
try
{
System.out.println("Thread+count="+count);
Thread.sleep(count*1000);
}
catch(Exception e)
{
e.printStackTrace();
}
}
};
t.start();
t.join();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Upvotes: 0
Views: 123
Reputation: 6713
Keep a list of threads you've spun up, and don't join until after they've all started:
List<Thread> threads = new ArrayList<Thread>();
for(int i=3;i<12;i=i+3)
{
Thread t=new Thread()
{
Random r=new Random();
int count=r.nextInt(10);
public void run()
{
try
{
System.out.println("Thread+count="+count);
Thread.sleep(count*1000);
}
catch(Exception e)
{
e.printStackTrace();
}
}
};
t.start();
threads.add(t);
}
// now wait for all threads to finish
for (Thread t : threads) {
t.join();
}
To explain the difference, I'll walk through the case you mentioned where the main method spins up two threads with count = 8
and count = 9
.
Joining in first for loop (your code) - 17 seconds:
for
count=8
join
and blocks for 8 seconds while thread worksfor
and starts second thread with count=9
join
and blocks for 9 seconds while thread worksJoining in second for loop - 9 seconds:
for
count=8
for
and starts second thread with count=9
for
completes, the two threads are off and runningfor
and calls join
on the first threadfor
and calls join
on the second threadNow you might say, what would happen if the first thread had count=9
and the second thread had count=8
? When joining in a second for loop, order does not matter, it will always be 9 seconds:
for
and calls join
on the first threadfor
and calls join
on the second threadUpvotes: 1