Tutorial :How do I make one Java thread return before some of its child threads finish?



Question:

I have 2 nested threads.

First thread starts multiple instances of second thread. Each second thread has to sleep for some time (5 seconds).

I want to start the first thread and return a message to user immediately, but it seems my first thread waits until all the children of second thread to finish.

How can I achieve this? Any help?


Solution:1

There are some common mistakes when dealing with java.lang.Thread.

  • Calling run on the thread instead of start. This is nothing magical about the run method.
  • Calling static methods on thread instances. Unfortunately this compiles. A common example is Thread.sleep. sleep is a static method and will always sleep the current thread, even if the code appears to be calling it on a different thread.

Rather than dealing with threads directly it is generally better to use a thread pool from java.util.concurrent.


Solution:2

What you should probably do, is create a single thread pool via Executors.newCachedThreadPool(). From your main thread submit Runnables (tasks) to the pool. Return to your main thread a list of Futures.

In Java there exists enough framework code that one rarely should need to deal with threads directly.


Solution:3

It may be helpful to see code. It depends on where you are putting Thread.sleep();.


Solution:4

Like someone else has pointed out with Threads you call start() which is a non-blocking call and actually gets the thread rolling. Calling run() will block until the run() method finishes. See the example code below;

public class Application {        public static void main(String[] args) {          FirstThread firstThread = new FirstThread();          firstThread.start();          System.out.println("Main Method ending");      }  }      public class FirstThread extends Thread {        public void run() {          for(int i = 0; i < 3; i++) {              SecondThread secondThread = new SecondThread(i);              secondThread.start();          }          System.out.println("FirstThread is finishing");      }  }    public class SecondThread extends Thread {        private int i;        public SecondThread(int i) {          this.i = i;      }        public void run() {            while(true) {              System.out.println("Second thread number " + i + " doing stuff here...");              // Do stuff here...                try {                  Thread.sleep(5000);               }              catch(InterruptedException ex){                  //ignore for sleeping}              }          }      }  }  

Which produces the output:

Main Method ending  Second thread number 0 doing stuff here...  Second thread number 1 doing stuff here...  FirstThread is finishing  Second thread number 2 doing stuff here...  Second thread number 0 doing stuff here...  Second thread number 2 doing stuff here...  Second thread number 1 doing stuff here...  


Solution:5

I replaced 'run' with 'start' in both first thread and second thread. It works fine now.

Thanks to all who responded with valueble suggestions.


Solution:6

public class FirstThread extends Thread {        public synchronized void run() {          for(int i = 0; i < 3; i++) {                  System.out.println("i="+i);          }          System.out.println("FirstThread is finishing");      }  }    public class SecondThread extends Thread {        public synchronized void run() {          for(int j = 0; j < 3; i++) {                  System.out.println("j="+j);          }          System.out.println("Second Thread is finishing");      }  }    public class Application {        public static void main(String[] args) {          FirstThread firstThread = new FirstThread();          SecondThread a=new SecondThread()          firstThread.start();          a.start();        }  }  

Output will be:

i=0  i=1  i=2  i=3  FirstThread is finishing    j=0  j=1  j=2  j=3  Second Thread is finishing  


Solution:7

You can use the Synchronized keyword which will use to run one thread completely

example

public synchronized void run() //which thread to run completely  {  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »