多執行緒基礎 6 執行緒池
阿新 • • 發佈:2018-11-09
- 執行緒池概述 * 程式啟動一個新執行緒成本是比較高的,因為它涉及到要與作業系統進行互動。而使用執行緒池可以很好的提高效能,尤其是當程式中要建立大量生存期很短的執行緒時,更應該考慮使用執行緒池。執行緒池裡的每一個執行緒程式碼結束後,並不會死亡,而是再次回到執行緒池中成為空閒狀態,等待下一個物件來使用
ExecutorService pool = Executors.newFixedThreadPool(2);//建立執行緒池 pool.submit(new MyRunnable());//將執行緒放進池子裡並執行 pool.submit(new MyRunnable()); pool.shutdown();
多執行緒(多執行緒程式實現的方式3)
public void print3() throws InterruptedException { r.lock(); if(flag != 3) { c3.await(); } System.out.print("hk"); System.out.print("\r\n"); flag = 1; c1.signal(); r.unlock(); public class Demo6_Callable { /** * @paramargs * @throws ExecutionException * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService pool = Executors.newFixedThreadPool(2);//建立執行緒池 Future<Integer> f1 = pool.submit(new MyCallable(100)); //將執行緒放進池子裡並執行 Future<Integer> f2 = pool.submit(new MyCallable(50)); System.out.println(f1.get()); System.out.println(f2.get()); pool.shutdown(); //關閉執行緒池 } } class MyCallable implements Callable<Integer> { private int num; public MyCallable(int num) { this.num = num; } @Override public Integer call() throws Exception { int sum = 0; for(int i = 1; i <= num; i++) { sum += i; } return sum; } }