1. 程式人生 > >【Java筆記】多執行緒實現簡單的非同步運算

【Java筆記】多執行緒實現簡單的非同步運算

實現Callable介面,重寫call()方法,使操作執行緒池時能帶有返回值的效果:

import java.util.concurrent.Callable;

public class GetSumCallable implements Callable<Integer> {
	private int a;

	public GetSumCallable(int a) {
		this.a = a;
	}

	public Integer call() {
		int sum = 0;
		for (int i = 1; i <= a; i++)
			sum += i;
		return sum;
	}
}

將執行緒放入執行緒池中,實現非同步運算:


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

public class GetSumThreadPoolDemo {
	public static void main(String[] args) throws Exception, ExecutionException {
		// 建立一個執行緒數為2的執行緒池
		ExecutorService es = Executors.newFixedThreadPool(2);
		// 將執行緒放入執行緒池中執行,將返回值封裝成Future介面實現類物件
		Future<Integer> f1 = es.submit(new GetSumCallable(100));
		Future<Integer> f2 = es.submit(new GetSumCallable(200));
		// 呼叫Future介面實現類物件,獲得封裝的值並輸出
		System.out.println(f1.get());
		System.out.println(f2.get());
		// 銷燬執行緒池
		es.shutdown();
	}
}