Get the result returned by the child thread (the use of Future)

When we start a thread in the main thread to process the task, usually this process is asynchronous, and the main thread responds directly to the result.
But if this process is synchronous, that is, the main thread waits for the response of the child thread before responding, what should be done?

A class that performs tasks, similar to implementing Runnable.
To set a generic, that is, the return result of the task
public class MyCallable implements Callable<Integer> {
	//return a random number
	@Override
	public Integer call() throws Exception {
		int result=new Random().nextInt(20);
		System.out.println(Thread.currentThread().getName()+"计算中...");
		//Simulation takes time
		Thread.sleep(2000);
		return result;
	}

}


main thread
public class Main {
	public static void main(String[] args) {
		//Set a future to return the result
		FutureTask<Integer> future=new FutureTask<>(new MyCallable());
		//Start the thread to start the task
		new Thread(future).start();
		
		System.out.println("before future get...");
		try {
			//If the task is not completed, the main thread will block here until a result is returned
			System.out.println(future.get());
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace ();
		}
		
		System.out.println("after future...");
	}
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326564198&siteId=291194637