views:

86

answers:

4

I have a function in which the processing is given over to a new thread.

The problem is the place where the function is called from does not wait for the function to return and promptly executes whatever code was there after the function call. How do I wait for the function to return so no code after it gets executed until its returned?

Hope I am not too vague. I am still new to the concept of multi-threading.

+1  A: 

Here is copy paste from JDK's description of Future interface

interface ArchiveSearcher { String search(String target); }
 class App {
   ExecutorService executor = ...
   ArchiveSearcher searcher = ...
   void showSearch(final String target)
       throws InterruptedException {
     Future<String> future
       = executor.submit(new Callable<String>() {
         public String call() {
             return searcher.search(target);
         }});
     displayOtherThings(); // do other things while searching
     try {
       displayText(future.get()); // use future
     } catch (ExecutionException ex) { cleanup(); return; }
   }
 }

The call executor.submit - forces task to be started in standalone thread. Invocation of future.get() will wait until task will be done and return the value.

Dewfy
A: 

If the function should wait for the new thread to terminate before returning, then that's what Thread.join() is for.

Michael Borgwardt
Thanks. This was what I wanted.
Goutham
A: 

Thats what Thread.join or Object.wait/notify is made for.

The calling code is infact in a different thread (The main thread). A new thread is created inside the function in question. I just want the main thread to wait for this function to return.

int main()
{
    Thread t = new Thread(...);
    t.start();
    t.join();
}

This does exactly what you want.

atamanroman
+1  A: 

What's the point of starting a new thread and waiting for it to complete? You get the same effect by just doing the execution in the current thread. It's another thing if you are actually launching a number of threads and want to wait for all of them to complete before moving forward.

The point of threads is concurrency, and you don't get any if you're just sitting idle waiting for one thread to complete.

Mikko Wilkman