執行緒(二)
阿新 • • 發佈:2018-12-09
執行緒一的基礎進行改造
/** * 生產者和消費者案例 採用synchronized wait() nitifyall() * @author fanfan * */ public class TestProductorAndConsumer2 { public static void main(String[] args) { Clerk1 cle = new Clerk1(); Productor1 pr = new Productor1(cle); Consumer1 cr = new Consumer1(cle); new Thread(pr,"生產者A").start(); new Thread(cr,"消費者B").start(); new Thread(pr,"生產者A1").start(); new Thread(cr,"消費者B1").start(); new Thread(pr,"生產者A3").start(); new Thread(cr,"消費者B3").start(); new Thread(pr,"生產者A4").start(); new Thread(cr,"消費者B4").start(); new Thread(pr,"生產者A5").start(); new Thread(cr,"消費者B5").start(); new Thread(pr,"生產者A7").start(); new Thread(cr,"消費者B7").start(); } } class Clerk1{ private int product = 0; //進貨 public synchronized void get() throws InterruptedException{ while(product>=1){ //為了避免虛假喚醒問題,應該總是使用在迴圈中 System.out.println("產品已滿"); this.wait(); } System.out.println(Thread.currentThread().getName()+";"+ ++product); this.notifyAll(); } //賣貨 public synchronized void sale() throws InterruptedException{ while(product <=0){ System.out.println("缺貨"); this.wait();; } System.out.println(Thread.currentThread().getName()+":"+ --product); this.notifyAll(); } } //生產者 class Productor1 implements Runnable{ private Clerk1 clerk; public Productor1(Clerk1 clerk){ this.clerk = clerk; } @Override public void run() { // TODO Auto-generated method stub for(int i = 0;i<20;i++){ try { Thread.sleep(200); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { clerk.sale(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } //消費者 class Consumer1 implements Runnable{ private Clerk1 clerk; public Consumer1(Clerk1 clerk){ this.clerk = clerk; } @Override public void run() { // TODO Auto-generated method stub for(int i = 0;i<20;i++){ try { clerk.get(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }