|
Hi
To stop the main thread from ending before any of the other threads, you can use two approaches
1. Increase the sleep time for main ie
public class driver_thread
{
public static void main(String[] args)
{
thread t1=new thread("A");
thread t2=new thread("B");
thread t3=new thread("C");
try
{
Thread.sleep(7500);
}
catch (InterruptedException e)
{
System.out.println("Main Thread Interrupted");
}
System.out.println("Main Thread Exiting");
}
}
This code would make the main thread to last the longest and by the time it ends, all the other threads would have already finished.
You might notice that through this approach although we are ensuring that main lasts the longest, the other threads can end at 3000 mili seconds or 5000 miliseconds or they can go on till 10,000 miliseconds. In the first two cases, although the threads have ended the main keeps sleeping for a longer period of time and, in the third case, the same problem is faced again.
To avoid that, the best approach is:
public class driver_thread
{
public static void main(String[] args)
{
thread t1=new thread("A");
thread t2=new thread("B");
thread t3=new thread("C");
try
{
t1.t.join();
t2.t.join();
t3.t.join();
}
catch (InterruptedException e)
{
System.out.println("Main Thread Interrupted");
}
System.out.println("Main Thread Exiting");
}
}
The join statements ensure that threads t1, t2 and t3 would end before the main thread.
Hopefully, this solves your problem.
Regards
|