【我的Java筆記】多執行緒_多執行緒實現的第三種方式(執行緒池)
阿新 • • 發佈:2019-01-24
Executors(工廠類)
方法:public static ExecutorService newFixedThreadPool(int nThreads)指定線上程池中多少條執行緒 注:此方法返回的是ExecutorService物件,該物件表示一個執行緒池,可以執行Runnable物件或者Callable物件代表的執行緒ExecutorService(介面)
方法:(此方法相當於Thread中的start() 方法) (1)Future<?> submit(Runnable task)提交任務 (2)<T> Future<T> submit(Callable<T> task) 該返回值表示非同步計算的結果Callable(介面)
方法:(1)V call() 注:此方法有返回值Future介面(用於計算)
方法: (1)V get() 等待計算完成,然後獲取其結果 注:獲取非同步計算的結果,返回值型別與Callable介面泛型相同*多執行緒實現的第三種方式操作步驟:
(1)自定義一個類實現Callable介面 (2)自定義類中重寫Callable介面中的 call() 方法 (3)在主執行緒中建立ExecutorService物件,並呼叫submit() 方法 (4)使用shutdown() 方法結束執行緒池// 自定義Callable類 import java.util.concurrent.Callable; public class MyCallable implements Callable<Object> { @Override public Object call() throws Exception { for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName()+"---"+i); } return null; } }
// 測試類
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CallableTest {
public static void main(String[] args) {
// 建立執行緒池對線,並指定2條執行緒
ExecutorService pool = Executors.newFixedThreadPool(2);
// 提交Callable任務
pool.submit(new MyCallable());
pool.submit(new MyCallable());
// 結束執行緒
pool.shutdown();
}
}
例2:執行緒求和
// 自定義Callable類
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 { // 返回與Callable介面泛型一致
// 定義最終結果變數
int sum = 0;
for (int x = 1; x <= number; x++) {
sum += x;
}
return sum;
}
}
// 測試類
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutionException;
public class CallableTest {
public static void main(String[] args) throws InterruptedException, ExecutionException {
// 建立執行緒池物件,利用工廠類:Executors
ExecutorService Pool = Executors.newFixedThreadPool(2);
// 提交2個非同步任務,分別計算1-100,1-200之間的和
Future<Integer> future1 = Pool.submit(new MyCallable(100));
Future<Integer> future2 = Pool.submit(new MyCallable(200));
// 分別呼叫Future介面中 get()方法,返回具體的結果
Integer v1 = future1.get();
Integer v2 = future2.get();
// 輸出結果
System.out.println("v1:" + v1);
System.out.println("v2:" + v2);
}
}