Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java 多執行緒:同步與死鎖、生產者與消費者完整範例

一、同步與死鎖

死鎖是什麼?A 手上握著 banana,B 手上握著 apple。

A 對 B 說:你把 apple 給我,我就把 banana 給你。

B 對 A 說:你把 banana 給我,我就把 apple 給你。

結果雙方都在等對方先行動,誰也不肯讓步——A 拿不到 apple,B 拿不到 banana。這個互等的迴圈就是死鎖。

用程式模擬這個故事。類別 A 代表 A 這個人:

public class A {
  public void say(){
    System.out.println("A said to B: if you give me the apple, I will give you the banana.");
  }
  public void get(){
    System.out.println("A get the apple.");
  }
}

類別 B 代表 B 這個人:

public class B {
  public void say(){
    System.out.println("B said to A: if you give me the banana, I will give you the apple.");
  }
  public void get(){
    System.out.println("B get the banana.");
  }
}

ThreadDeadLock 負責製造死鎖:

public class ThreadDeadLock implements Runnable{
  private static A a=new A();
  private static B b=new B();
  public boolean flag=false;
  public void run(){
    if(flag){
      synchronized(a){
        a.say();
        try{
          Thread.sleep(500);
        }catch(InterruptedException e){
          e.printStackTrace();
        }
        synchronized(b){
          a.get();
        }
      }
    }else{
      synchronized(b){
        b.say();
        try{
          Thread.sleep(500);
        }catch(InterruptedException e){
          e.printStackTrace();
        }
        synchronized(a){
          b.get();
        }
      }
    }
  }
}

主程式:

public class Main{
  public static void main(String[] args){
    ThreadDeadLock t1=new ThreadDeadLock();
    ThreadDeadLock t2=new ThreadDeadLock();
    t1.flag=true;
    t2.flag=false;
    Thread thA=new Thread(t1);
    Thread thB=new Thread(t2);
    thA.start();
    thB.start();
  }
}

執行結果停在這裡就不動了:

A said to B: if you give me the apple, I will give you the banana.
B said to A: if you give me the banana, I will give you the apple.

兩個執行緒互相持有對方要的鎖,程式從此無法推進。這也說明了一個實務原則:多把鎖的取得順序必須一致,否則遲早碰上死鎖。

二、生產者與消費者

這個經典問題的模型很直白:生產者不停生產產品,消費者不停取走產品。

先定義產品類別 Product:

public class Product {
  private String name="product";
  private boolean flag=false;
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public synchronized void set(String name){
    if(!flag){
      try{
        super.wait();
      }catch(InterruptedException e){
        e.printStackTrace();
      }
    }
    this.setName(name);
    try{
      Thread.sleep(300);
    }catch(InterruptedException e){
      e.printStackTrace();
    }
    flag=false;
    super.notify();
  }
  public synchronized void get(){
    if(flag){
      try{
        super.wait();
      }catch(InterruptedException e){
        e.printStackTrace();
      }
    }
    try{
      Thread.sleep(300);
    }catch(InterruptedException e){
      e.printStackTrace();
    }
    System.out.println(this.getName());
    flag=true;
    super.notify();
  }
}

這裡用 wait/notify 搭配一個旗標 flag:flag 為 true 代表可以生產但不可取走,此時若消費者搶到鎖就必須等待;flag 為 false 則相反,生產者必須等待。

Producer 類別:

public class Producer implements Runnable{
  private Product product=null;
  public Producer(Product product){
    this.product=product;
  }
  public void run(){
    for(int i=0;i<50;++i){
      this.product.set("product");
    }
  }
}

Consumer 類別:

public class Consumer implements Runnable{
  private Product product=null;
  public Consumer(Product product){
    this.product=product;
  }
  public void run(){
    for(int i=0;i<50;++i){
      try{
        Thread.sleep(100);
      }catch(InterruptedException e){
        e.printStackTrace();
      }
      this.product.get();
    }
  }
}

主程式:

public class Main{
  public static void main(String[] args){
    Product product=new Product();
    Producer pro=new Producer(product);
    Consumer con=new Consumer(product);
    new Thread(pro).start();
    new Thread(con).start();
  }
}

於是流程變成:生產者每生產一件,消費者就取走一件;消費者取完一件後必須停下腳步,等生產者補貨。透過共享物件的 wait/notify,兩個執行緒的節奏被牢牢綁在一起,既不會空轉,也不會重複消費。

Copyright © Linux教程網 All Rights Reserved