Java多執行緒-執行緒池的使用與執行緒總結(狂神說含程式碼)
阿新 • • 發佈:2021-12-15
使用執行緒池
-
背景:經常建立和銷燬、使用量特別大的資源,比如併發情況下的執行緒,對效能影響很大
-
思路:提前建立好多個執行緒,放入執行緒池中,使用時直接獲取,使用完放回池中。可以避免頻繁建立銷燬,實現重複利用。類似生活中的公共交通工具。
-
好處:
- 提高響應速度(減少了建立新執行緒的時間)
- 降低資源消耗(重複利用執行緒池中執行緒,不需要每次都建立)
- 便於執行緒管理(...)
- cornPoolSize:核心池的大小
- maximumPoolSize:最大執行緒數
- keepAliveTime:執行緒沒有任務最多保持多長時間後就會終止
-
JDK5.0起提供了執行緒池相關API:ExecutorService和Executors
-
ExecutorService:真正的執行緒池介面。常見子類ThreadPoolExecutor
- void execute(Runnable command):執行任務、命令,沒有返回值,一般用來執行Runnable
Future submit(Callcable task):執行任務,有返回值,一般又來執行Callable - void shutdown():關閉連線池
- Executors:工具類,執行緒池的工廠類,用於建立並返回不同型別的執行緒池
package com.thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; //測試執行緒池 public class TestPool { public static void main(String[] args) { //1.建立服務,建立執行緒池 //newFixedThreadPool 引數為執行緒池的大小 ExecutorService service = Executors.newFixedThreadPool(10); service.execute(new MyThread()); service.execute(new MyThread()); service.execute(new MyThread()); service.execute(new MyThread()); //關閉連線 service.shutdown(); } } class MyThread implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()); } }
package com.thread.gaoji; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; //回顧總結執行緒的建立 public class ThreadNew { public static void main(String[] args) { new MyThread1().start(); new Thread(new Mythread2()).start(); FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyThread3()); new Thread(futureTask).start(); try { Integer integer = futureTask.get(); System.out.println(integer); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } //1.繼承Thread類 class MyThread1 extends Thread{ @Override public void run() { System.out.println("MyThread"); } } //2.實現runnable介面 class Mythread2 implements Runnable{ @Override public void run() { System.out.println("MyThread2"); } } //實現callable介面 class MyThread3 implements Callable<Integer>{ @Override public Integer call() throws Exception { System.out.println("MyThread3"); return 100; } }