开发者

How to make the current thread wait for a function to return in java?

开发者 https://www.devze.com 2023-01-14 19:18 出处:网络
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 what

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开发者_StackOverflow社区 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.


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.


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消