Java – how do I pass parameters to a thread and get the return value?
•
Java
public class CalculationThread implements Runnable {
public class CalculationThread implements Runnable { int input; int output; public CalculationThread(int input) { this.input = input; } public void run() { output = input + 1; } public int getResult() { return output; } }
Other places:
Thread thread = new Thread(new CalculationThread(1)); thread.start(); int result = thread.getResult();
Of course, thread GetResult () does not work (it attempts to call this method from the thread class)
You got what I wanted How can I achieve this in Java?
Solution
This is the job of the thread pool You need to create a callable < R > which is a value returned by runnable and sent to the thread pool
The result of this operation is future < R > This is a pointer to this job. It will contain the calculated value. If the job fails, it will not
public static class CalculationJob implements Callable<Integer> { int input; public CalculationJob(int input) { this.input = input; } @Override public Integer call() throws Exception { return input + 1; } } public static void main(String[] args) throws InterruptedException { ExecutorService executorService = Executors.newFixedThreadPool(4); Future<Integer> result = executorService.submit(new CalculationJob(3)); try { Integer integer = result.get(10,TimeUnit.MILLISECONDS); System.out.println("result: " + integer); } catch (Exception e) { // interrupts if there is any possible error result.cancel(true); } executorService.shutdown(); executorService.awaitTermination(1,TimeUnit.SECONDS); }
Print:
result: 4
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码