Shubha:If yes, the chld thread should kill itself and return to the main thread.
What do you mean by the child thread should return to the main thread? A thread once started runs on its own and does not return as a method call.
I dont think killing the thread is the write
word to use. If the run method returns, the thread stops, i think this is what you want.
Shubha:If the API does not complete execution within 30 mts, then the child thread should throw an exception to the main program and the main program should return.
Again, a thread once started runs on its own and can not throw an exception to the thread that started it.(A difference between starting a thread and calling a normal method.)
Shubha:I am confused how to monitor the state of main thread from child thread.
This is one thing that probably is a valid question.
So, from your post there is the following that I understand:
1) You have to do some task in a separate thread that you expect to complete withing 30 mins. You call this the main thread. (Main thread is mostly referred to as the thread that calls the main() method of the class that is used to launch the JVM. So, this terminology is a little misleading.)
2) For making sure that the above thread does not run for more than 30 mins, you have spawned one more thread that you call as child thread.
For avoding confusion, I will call the first thread as T1 and the second one as T2.
You can achieve what you want by calling
join(long) on T1. This will make the calling thread to wait (for a maximum of the time duration) for T1 to finish.
You can modify the code of T1 to update a shared variable denoting the process completion status when finished.
After the thread that called join() on T1 returns, it can check the shared variable value. If it is done then quietly process else interrupt T1 or signal T1 to stop. (stop() is deprecated so you can not forcibly stop a thread)
Below is a sample code. This code assumes that the thread that starts T1 does not have any other work to do. So, it just calls join with T1. If this is not the case for you, you can spawn T2 that just joins on T1.