开发者

How do i get returned value from inner Thread Runnable method in Java?

How do i assign Status with CallMe() using isFinish() to have returned value true?

public static boolean isFinish ()
{    
  boolean Status = false;
  new Thread(new Runnable()
  {
    public void run()
    {
      /* This shell return true or false 
       * How do you keep it in Status
       */
      CallMe(); 
    }
  }).start();

  /* How can i get the true or false exactly from CallMe? here */
  retu开发者_JS百科rn Status;
}

public static boolean CallMe()
{
  /* some heavy loads ... */
  return true;
}


There are two ways of doing this. The first is to use a future computation result and the other is to have a shared variable. I think that the first method is much cleaner than the second, but sometimes you need to push values to the thread too.

  • Using a RunnableFuture.

FutureTask implements a RunnableFuture. So you create that task which, once executed, will have a value.

RunnableFuture f = new FutureTask(new Callable<Boolean>() {
  // implement call
});
// start the thread to execute it (you may also use an Executor)
new Thread(f).start();
// get the result
f.get();
  • Using a holder class

You create a class holding a value and share a reference to that class. You may create your own class or simply use the AtomicReference. By holder class, I mean a class that has a public modifiable attribute.

// create the shared variable
final AtomicBoolean b = new AtomicBoolean();
// create your thread
Thread t = new Thread(new Runnable() {
  public void run() {
    // you can use b in here
  }
});
t.start();
// wait for the thread
t.join();
b.get();


You rewrite the code to use Callable<Boolean> and obtain a Future when launching the Runnable.

Futures allow the launching thread to properly check that the value is ready and read it asynchronously. You could do the coding by hand, but since Future is now part of the standard JVM libraries, why would you (outside of a programming class)?


Working with raw threads, you could implement Runnable with a named type, and store the value in it.

class MyRunnable implements Runnable {
   boolean status;

   public void run() {
      ...
   }
}

However, if you're working with another thread, you'll have to synchronize in some way.

It would be easier to use the higher-level tools provided by the java.util.concurrent hierarchy. You can submit a Callable to an Executor, and get a Future. You can ask the Future if it's done, and get the result. There's an Oracle tutorial here.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜