How to call a method immediately after the completion of the stream ()?

I want to call a method that returns a string value. In fact, this string value is an instance variable, and the run method is a string value.

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

How am i doing this ??

Plz someone help me ..

Saravanan

+4
source share
3 answers
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(); } } 
+5
source

Discard Callable , which is Runnable, which can return a result.

You use it as follows:

You write Callable instead of Runnable, for example:

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

You kick it by sending it to the ExecutionService:

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

You return a FutureTask handle that will contain the result after the task completes:

 Integer result = task.get (); 

FutureTask provides more methods, such as cancel , isDone and isCancelled , to cancel execution and request status. The get method itself blocks and waits for the task to complete. check out the details of javadoc.

+9
source

Instead, use Callable<String> , send it to the ExecutorService , and then call get() on the Future<String> , which it returns when it is sent.

+1
source

All Articles