I am using more than 5 threads in my code once the main method execute all the threads are called at the beginning, once all threads are active i want main thread to stop until all child threads are dead.If i use join() method for any thread then all other child methods are also getting paused.In my case i need to pause main thread alone.
Asked
Active
Viewed 4,034 times
0
-
3Can you put in some code? I would like to see how and on what are you calling the join method. The join method is the best way to achieve what you want to do. You must probably be doing something wrong for it to not work. – Aditya Gupta Jul 06 '16 at 06:55
-
3`If i use join() method for any thread then all other child methods are also getting paused`, other threads should not pause. seem you did something incorrect. – TomN Jul 06 '16 at 07:05
2 Answers
3
You need to join
after all threads have already started. i.e:
for(int i = 0; i < numThreads; i++) {
threads[i].start();
}
And only then:
for(int i = 0; i < numThreads; i++) {
threads[i].join();
}
The above will work.

Idos
- 15,053
- 14
- 60
- 75
0
You should use CountDownLatch
for this:
For main thread
CountDownLatch latch = new CountDownLatch(5); //for 5 threads
for(int i = 0; i < 5; i++) {
new Thread(new Worker("thread " + i, latch)).start();;
}
latch.await(); //wait till all workers are dead
For worker thread
priavte CountDownLatch;
public Worker(String name, CountDownLatch latch) {
this.name = name;
this.latch = latch;
}
public void run() {
try {
System.out.println(name + " done!");
} finally {
latch.countDown();//count down
}
}

Ruther
- 1
- 2