I have a function that needs to perfom two operations, one which finishes fast and one which takes a long time to run. I want to be able to delegate the long running operation to a thread and I dont care when the thread finishes, but the threads needs to complete. I implemented this as shown below , but, my secondoperation never gets done as the function exits after the start() call. How I can ensure that the function returns but the second operation thread finishes its execution as well and is not dependent on the parent thread ?
public void someFunction(String data)
{
smallOperation()
SecondOperation a = new SecondOperation();
Thread th = new Thread(a);
th.Start();
}
class SecondOperation implements Runnable
{
public void run(){
// doSomething long running
}
}
if i get your question right , you wanna invoke
someFunction()
, execute the shortsmallOperation()
, run a thread to theSecondOperation
and make sure that when returned from this function , theSecondOperation
is completed .if the flow i suggested is correct , u only need to add the following line :
take a look at this article , it states that "When we invoke the join() method on a thread, the calling thread goes into a waiting state. It remains in a waiting state until the referenced thread terminates" . which i think what you trying to accomplish
if its not the case and you wanna be notified when the
SecondOperation
terminates , i suggest you use asyncTaskIt may be late to answer this question, but here is the working solution. Just add the runnables to ExecutorService.
The JVM will not exit before the thread terminates. This code that you posted does not even compile; perhaps the problem is in your actual code.
IF your second function is not getting done it has nothing to do with your function returning. If something calls
System.exit()
or if your function throws an exception, then the thread will stop. Otherwise, it will run until it is complete, even if your main thread stops. That can be prevented by setting the new thread to be a daemon, but you are not doing that here.Solution using modern Java
If
someFunction
is called, the JVM will run thelongOperation
iflongOperation()
does not throw an exception andlongOperation()