package cn.itcast_10;
import java.util.concurrent.Callable;
/*
* 執行緒求和案例
*/
public class MyCallable implements Callable<Integer> {
private int number;
public MyCallable(int number) {
this.number = number;
}
@Override
public Integer call() throws Exception {
int sum = 0;
for (int x = 1; x <= number; x++) {
sum += x;
}
return sum;
}
}
package cn.itcast_10;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/*
* 多執行緒實現的方式3:
* A:建立一個執行緒池物件,控制要建立幾個執行緒物件。
* public static ExecutorService newFixedThreadPool(int nThreads)
* B:這種執行緒池的執行緒可以執行:
* 可以執行Runnable物件或者Callable物件代表的執行緒
* 做一個類實現Runnable介面。
* C:呼叫如下方法即可
* Future<?> submit(Runnable task)
* <T> Future<T> submit(Callable<T> task)
* D:我就要結束,可以嗎?
* 可以。
*/
public class CallableDemo {
public static void main(String[] args) throws InterruptedException, ExecutionException {
// 建立執行緒池物件
ExecutorService pool = Executors.newFixedThreadPool(2);
// 可以執行Runnable物件或者Callable物件代表的執行緒
Future<Integer> f1 = pool.submit(new MyCallable(100));
Future<Integer> f2 = pool.submit(new MyCallable(200));
// V get()
Integer i1 = f1.get();
Integer i2 = f2.get();
System.out.println(i1);
System.out.println(i2);
// 結束
pool.shutdown();
}
}