多線程之間通信及線程池

線程通信

  • 應用場景:生產者和消費者問題

    • 假設倉庫中只能存放一件產品,生產者將生產出來的產品放入倉庫,消費者將倉庫中產品取走消費
    • 如果倉庫中沒有產品,則生產者將產品放入倉庫,否則停止生產並等待,直到倉庫中的產品被消費者取走為止
    • 如果倉庫中放有產品,則消費者可以將產品取走消費,否則停止消費並等待,直到倉庫中再次放入產品為止
  • 這是一個線程同步問題,生產者和消費者共享同一個資源,並且生產者和消費者之間相互依賴,互為條件。

    • 對於生產者,沒有生產產品之前,要通知消費者等待。而生產了產品之後,又需要馬上通知消費者消費
    • 對於消費者,在消費之後,要通知生產者已經結束消費,需要生產新的產品以供消費
    • 在生產者消費者問題中,僅有synchronized是不夠的
      • synchronized可阻止並發更新同一個共享資源,實現了同步
      • synchronized不能用來實現不同線程之間的消息傳遞(通信)
  • 解決線程之間通信問題的方法

方法名 作用
wait() 表示線程一直等待,知道其他線程通知,與sleep不同,會釋放鎖
wait(long timeout) 指定等待的毫秒數
notify() 喚醒一個處於等待狀態的線程
notifyAll() 喚醒同一個對象上所有調用wait()方法的線程,優先級別高的線程優先調度

解決方式1

並發協作模型「生產者/消費者模式」—>管程法

  • 生產者:負責生產數據的模塊(可能是方法,對象,線程,進程);
  • 消費者:負責處理數據的模塊(可能是方法,對象,線程,進程);
  • 緩衝區:消費者不能直接使用生產者的數據,他們之間有個緩衝區,生產者將生產好的數據放入緩衝區,消費者從緩衝區拿出數據

//測試:生產者消費者模型-->利用緩衝區解決:管程法

//生產者,消費者,產品,緩衝區
public class TestPC {

    public static void main(String[] args) {
        SynContainer container = new SynContainer();

        new Productor(container).start();
        new Consumer(container).start();
    }
}

//生產者
class Productor extends Thread{
    SynContainer container;

    public Productor(SynContainer container){
        this.container = container;
    }

    //生產
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            container.push(new Chicken(i));
            System.out.println("生產了"+i+"只雞");
        }
    }
}

//消費者
class Consumer extends Thread{
    SynContainer container;

    public Consumer(SynContainer container){
        this.container = container;
    }
    
    //消費
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消費了-->"+container.pop().id+"只雞");
        }
    }
}

//產品
class Chicken{
    int id;//產品編號

    public Chicken(int id) {
        this.id = id;
    }
}

//緩衝區
class SynContainer{

    //需要一個容器大小
    Chicken[] chickens = new Chicken[10];
    //容器計數器
    int count = 0;

    //生產者放入產品
    public synchronized void push(Chicken chicken){
        //如果容器滿了,就需要等待消費者消費
        if (count==chickens.length){
            //通知消費者消費,生產者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果沒有滿,我們就需要丟入產品
        chickens[count] = chicken;
        count++;

        //可以通知消費者消費了
        this.notifyAll();
    }

    //消費者消費產品
    public synchronized Chicken pop(){
        //判斷能否消費
        if (count==0){
            //等待生產者生產,消費者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //如果可以消費
        count--;
        Chicken chicken = chickens[count];

        //吃完了,通知生產者生產
        this.notifyAll();
        return chicken;
    }
}

解決方式2

  • 並發協作模式「生產者/消費者模式」—>信號燈法
//測試生產者消費者問題2:信號燈法,標誌位解決
public class TestPC2 {

    public static void main(String[] args) {
        TV tv = new TV();
        new Player(tv).start();
        new Watcher(tv).start();

    }
}

//生產者-->演員
class Player extends Thread{
    TV tv;
    public Player(TV tv){
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if (i%2==0){
                this.tv.play("快樂大本營播放中");
            }else {
                this.tv.play("抖音:記錄美好生活");
            }
        }
    }
}

//消費者-->觀眾
class Watcher extends Thread{
    TV tv;
    public Watcher(TV tv){
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            tv.watch();
        }
    }
}

//產品-->節目
class TV{
    //演員表演,觀眾等待
    //觀眾觀看,演員等待
    String voice;//表演的節目
    boolean flag = true;

    //表演
    public synchronized void play(String voice){

        if (!flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("演員表演了:"+voice);
        //通知觀眾觀看
        this.notifyAll();//通知喚醒
        this.voice = voice;
        this.flag = !this.flag;

    }

    //觀看
    public synchronized void watch(){
        if (flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("觀看了:"+voice);
        //通知演員表演
        this.notifyAll();
        this.flag = !this.flag;
    }
}

線程池

使用線程池

  • 背景:經常創建和銷毀、使用量特別大的資源,比如並發情況下的線程,對性能影響很大。
  • 思路:提前創建好多個線程,放入線程池中,使用時直接獲取,使用完放回池中。可以避免頻繁創建銷毀、實現重複利用。類似生活中的公共交通工具。
  • 好處:
    • 提高響應速度(減少了創建新線程的時間)
    • 降低資源消耗(重複利用線程池中線程,不需要每次都創建)
    • 便於線程管理(…)
      • corePoolSize:核心池的大小
      • maximumPoolSize:最大線程數
      • keepAliveTime:線程沒有任務時最多保持多長時間後會終止
  • JDK5.0起提供了線程池相關API:ExexutorServiceExecutors
  • ExecutorService:真正的線程池接口。常見子類ThreadPoolExecutor
    • void execute(Runnable command):執行任務/命令,沒有返回值,一般用來執行Runnable
    • Future submit(Callable task):執行任務,有返回值,一般又來執行Callable
    • void shutdown():關閉連接池
  • Executors:工具類、線程池的工廠類,用於創建並返回不同類型的線程池
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());

        //2.關閉鏈接
        service.shutdown();
    }
}

class MyThread implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}
Tags: