1. 程式人生 > >執行緒callable方法

執行緒callable方法

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;

class MyCallable implements Callable<Integer> {

	private Integer number;

	public MyCallable(Integer number) {
		this.number = number;
	}

	@Override
	public Integer call() throws Exception {
		Integer sum = 0;
		for (int x = 1; x <= number; x++) {
			sum += x;
		}
		return sum;
	}
}

class Mycallable implements Callable<String> {

	@Override
	public String call() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}

class CallableDemo {

	public static void main(String[] args) throws ExecutionException, InterruptedException {
		// 建立執行緒池物件
		ExecutorService pool = Executors.newFixedThreadPool(2);
		// 可以執行 Runnable 或者 Callable 物件代表的執行緒
		Future<Integer> future1 = pool.submit(new MyCallable(100));
		Future<Integer> future2 = pool.submit(new MyCallable(200));
		// TODO: 16/7/19
		Integer i1 = future1.get();
		Integer i2 = future2.get();
		System.out.println(i1);
		System.out.println(i2);
		// 結束
		pool.shutdown();
	}
}