Java: get value from stream ...?

How to return a variable from thead (I also have thread descriptors). Static variables will not work in this case.

Refresh . Here is one twist, how can I do this without having to block and wait for the result? I need to be able to poll the created thread and kill it if it hangs for too long (e.g.> 1 minute), and then continue in the main thread if the generated thread takes too long.

+4
source share
2 answers

Use Callable<V> instead of Thread (or Runnable ) so you can get the result as Future<V> and use ExecutorService to call it.

Here is SSCCE , just copy ' paste'n'run :

 package com.stackoverflow.q2413389; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Test { public static void main(String... args) throws Exception { ExecutorService executor = Executors.newCachedThreadPool(); List<Future<String>> results = executor.invokeAll(Arrays.asList(new Task())); for (Future<String> result : results) { System.out.println(result.get()); // Prints "myResult" after 2 seconds. } executor.shutdown(); } } class Task implements Callable<String> { public String call() throws Exception { Thread.sleep(2000); // Do your running task here, this example lasts 2 seconds. return "myResult"; } } 

Update : according to your update with the question of how to kill it after a timeout, use ScheduledExecutorService instead. The code has changed a bit here:

 ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); List<Future<String>> results = executor.invokeAll(Arrays.asList(new Task()), 1, TimeUnit.SECONDS); // Timeout of 1 second. for (Future<String> result : results) { if (!result.isCancelled()) { System.out.println(result.get()); // Won't be printed as the "actual" processing took 2 seconds. } else { System.out.println("Task timed out."); } } executor.shutdown(); 
+13
source

If I understand your question (how to access the value of a member of a thread object), you can use this simple approach:

MyObject a = new MyObject(); new Thread(a).start();

Remember to implement the Runnable interface for MyObject and have the corresponding Getters.

If you want to return a variable, you can create a member in the class AND do a while loop until the thread completes execution.

+1
source

Source: https://habr.com/ru/post/1303617/


All Articles