javamultithreading

How to pass a parameter to a thread and get a return value?


How to pass a parameter to a thread and get a return value?

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;
    }
}

Somewhere else:

Thread thread = new Thread(new CalculationThread(1));
thread.start();
int result = thread.getResult();

Of course, thread.getResult() doesn't work (it tries to invoke this method from the Thread class).

How can I achieve this in Java?


Solution

  • This a job for thread pools. You need to create a Callable<R> which is Runnable returning a value and send it to a thread pool.

    The result of this operation is a Future<R> which is a pointer to this job which will contain a value of the computation, or will not if the job fails.

    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);
    }
    

    Prints:

    result: 4