1. 程式人生 > >多執行緒 : 使用 Future 獲取執行緒返回結果

多執行緒 : 使用 Future 獲取執行緒返回結果

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class FetureTest {

	public static void main(String[] args) {
		ExecutorService threadPool = Executors.newFixedThreadPool(3);
		Future<Integer> future = threadPool.submit(new Callable<Integer>() {

			@Override
			public Integer call() throws Exception {
				return new Random().nextInt(500);
			}

		});
		try {
			// 獲取結果
			future.get();
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}

	}
}