2

I have to run multiple threads ||ly and after execution of all these thread main thread continue. For eg I have one main thread and 3 sub threads, my need is

run main thread
pause main thread
run all 3 sub threads ||ly
after complition resume main thread

I create a class extends Thread and call start method of all these thread but it doesn't solve my problem.

My Code:

for (MyThread myThread : myThreads) {
    myThread.start();
}

Thanks for help.

Ashish Aggarwal
  • 3,018
  • 2
  • 23
  • 46

4 Answers4

3

Try using Thread.join();

public class ThreadDemo implements Runnable {

   public void run() {

      Thread t = Thread.currentThread();
      System.out.print(t.getName());
      //checks if this thread is alive
      System.out.println(", status = " + t.isAlive());
   }

   public static void main(String args[]) throws Exception {

      Thread t = new Thread(new ThreadDemo());
      // this will call run() function
      t.start();
      // waits for this thread to die
      t.join();
      System.out.print(t.getName());
      //checks if this thread is alive
      System.out.println(", status = " + t.isAlive());
   }
} 

Output:

Thread-0, status = true
Thread-0, status = false

Here is a stack-over-flow link for reference.

Community
  • 1
  • 1
Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38
  • Linking stacks is a perfectly valid way to answer, particularly a duplicate question (which certainly is). – Gusdor Aug 12 '13 at 12:52
  • @Gusdor NO!!! link-only answers are not welcome! Some people flag those recklessly, and they should. I'm more patient (normally). – John Dvorak Aug 12 '13 at 12:54
  • @Gusdor if it's a duplicate question, then you should vote to close or flag to close. Additionally, you can downvote the question for the lack of research. – John Dvorak Aug 12 '13 at 12:56
  • I would be much happier with a link to an original stack rather than a copy-paste of someone else's answer. That means that even if my search queries did not give me the right result, i can still up-vote the answer that worked for me and the original question itself. – Gusdor Aug 12 '13 at 13:34
  • I agree with you @Gusdor , but this answer is not copied from the link given below. :-) – Ankur Shanbhag Aug 12 '13 at 13:39
1

Forget 'pausing' threads. Your schedule should be

  1. Initiate X actions on X threads
  2. Wait for all threads to finish
  3. Process results (if any)

So how do you wait for threads to finish? You need a synchronization mechanism. These are often OS level 'flags' called semaphores but the java library gives you a few ways of doing it. You will get a lot out of this series, particularly part 2: Thread Synchronization

Gusdor
  • 14,001
  • 2
  • 52
  • 64
  • 1
    Please don't just post a link or two and walk away. Some code example would be nice. Links disappear over time, and they cost an extra click even if they don't disappear. Not to mention that examples in the tutorial is probably way more complex than what the asker actually needs. – John Dvorak Aug 12 '13 at 12:45
  • What the OP needs is a thorough shakedown of threading. This very short series taught me all I needed to know about java threading, scheduling and synchronization. It was posted in 2002! 11 years, no disappearance. I don't expect this to be the definitive answer (good luck defining that) but shining light on a great resource has value of its own. "...cost an extra click". Good grief. Should we put the internet on one page with anchors? A whole library in one book? – Gusdor Aug 12 '13 at 12:50
  • Or, you could actually answer OP's question (ideally with some explanation) and include the link as "further reading" – John Dvorak Aug 12 '13 at 12:53
  • …but the correct answer (using Thread.join()) has already been given, no need repeating that. The further reading on threading seems a good idea for me, too since the OP would benefit from that more than from another answer telling him to use Thread.join(). Having said that, Gusdors answer would fit better as a comment than an answer. I have received downvotes for soemthing like this in the past. – Ralf H Aug 12 '13 at 12:56
  • @RalfH or, it could be formulated as an addendum: "in addition to [Gusdor's great answer] I also recommend reading some tutorials like [the one by Sun]". Yes. It does sound more like a comment, but I'd likely let it slip. – John Dvorak Aug 12 '13 at 12:58
  • Comments taken on board folks. In future i will put this sort of 'answer' in a comment. – Gusdor Aug 12 '13 at 13:30
0

You can call join() on the threads. Assuming that your threads are in myThreads and you don't want your thread to be interruptible

// ...
// create threads and start them
// ...
for (Thread t : myThreads) {
    while (t.isAlive()) {
        try {
            t.join();
        } catch (InterruptedException e) { }
    }
}

If it should be interruptible:

// ...
// create threads and start them
// ...
for (Thread t : myThreads)
    t.join();
bennihepp
  • 262
  • 1
  • 11
  • 1
    You go to the extra trouble of making this code uninterruptible. That's a rarity, usually people make their code uninterruptible by accident and/or lack of understanding. – Marko Topolnik Aug 12 '13 at 12:35
  • If the requirement is to wait for all 3 sub threads to complete I think it's better to do it this way. Just in case. – bennihepp Aug 12 '13 at 12:36
  • 1
    The requirement will be fully, and may I say better, satisfied if the code allows itself to be interrupted. Interrupts don't come out of the blue, they must be issued as a result of an express intent to interrupt a stuck thread. – Marko Topolnik Aug 12 '13 at 12:37
  • If going the interruptible route, you don't need the `t.isAlive()` check at all. The code is in fact very simple: `for (Thread t : threads) t.join();` There *will* be this nagging issue of handling the checked `InterruptedException`, but that's a separate concern. A method may just declare to throw it. – Marko Topolnik Aug 12 '13 at 12:42
  • 'You have to call join() on the threads.' - 'have to'? not really, no. – Martin James Aug 12 '13 at 12:50
0

CountDownLatch is much more flexible mechanism then Thread.join. It does exactly what you want. Prefer java.util.concurrent.* instead of old builtin java techniques.

Advantages:

  1. Using CDL you deal with a single object instead of bunch of thread. That could simplify code.
  2. It has a getCount() method which could be used to implement progress bar. With joins its much more complicated.
  3. await(long timeout, TimeUnit unit) could be considered more comfortable than join(long millis)
Mikhail
  • 4,175
  • 15
  • 31
  • 1
    It would seem that `Thread#join` also does exactly what OP wants. What more does the CDL have to offer? Does it do exactlier what OP wants? In less lines of code? More robustly? – Marko Topolnik Aug 12 '13 at 13:17
  • Well, I think the main difference will be in lines of code between thees approaches. For a HelloWorld example it does not matter, but for a large project it does. – Mikhail Aug 12 '13 at 13:27
  • OP's problem is solved "for real" using an `ExecutorService` and not a `CountDownLatch`. – Marko Topolnik Aug 12 '13 at 13:29
  • ExecutorService is a much more complicated framework than CDL. Anyway without real case thees all are just suggestions. One thing Iam sure about is that join is the least suitable way. – Mikhail Aug 12 '13 at 13:42
  • It may be more complicated inside, but its API makes the whole task simpler and less error-prone. Not to say *way* more flexible. – Marko Topolnik Aug 12 '13 at 13:43