Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call a method immediately after thread run() ends?

I want to call a method that returns a string value. Actually this string value is an instance variable, and run() method put the value of the string.

So, I want to call a method to get the string value updated by thread run() method..

How can I do it...?

like image 820
Saravanan Avatar asked Dec 04 '22 11:12

Saravanan


2 Answers

Check out Callable which is a Runnable that can return a result.

You use it like this:

You write a Callable instead of a Runnable, for example:

public class MyCallable implements Callable<Integer> {
  public Integer call () {
    // do something that takes really long...
    return 1;
  }
}

You kick it of by submitting it to an ExecutionService:

ExecutorService es = Executors.newSingleThreadExecutor ();
Future<Integer> task = es.submit(new MyCallable());

You get back the FutureTask handle which will hold the result once the task is finished:

Integer result = task.get ();

FutureTask provides more methods, like cancel, isDone and isCancelled to cancel the execution and ask for the status. The get method itself is blocking and waits for the task to finish. check out the javadoc for details.

like image 71
Tim Büthe Avatar answered Jan 05 '23 15:01

Tim Büthe


class Whatever implements Runnable {
    private volatile String string;

    @Override
    public void run() {
        string = "whatever";
    }

    public String getString() {
        return string;
    }

    public void main(String[] args) throws InterruptedException {
        Whatever whatever = new Whatever();
        Thread thread = new Thread(whatever);
        thread.start();
        thread.join();
        String string = whatever.getString();
    }
}
like image 27
Steve Emmerson Avatar answered Jan 05 '23 15:01

Steve Emmerson