GUC-13 生產者和消費者案例-舊

 

/*
 * 生產者和消費者案例
 */
public class TestProductorAndConsumer {

    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        
        Productor pro = new Productor(clerk);
        Consumer cus = new Consumer(clerk);
        
        new Thread(pro, "生產者 A").start();
        new Thread(cus, "消費者 B").start();
        
        new Thread(pro, "生產者 C").start();
        new Thread(cus, "消費者 D").start();
    }
    
}

/*//店員
class Clerk{
    private int product = 0;
    
    //進貨
    public synchronized void get(){//循環次數:0
        while(product >= 1){//爲了不虛假喚醒問題,應該老是使用在循環中
            System.out.println("產品已滿!");
            
            try {
                this.wait();
            } catch (InterruptedException e) {
            }
            
        }
        
        System.out.println(Thread.currentThread().getName() + " : " + ++product);
        this.notifyAll();
    }
    
    //賣貨
    public synchronized void sale(){//product = 0; 循環次數:0
        while(product <= 0){
            System.out.println("缺貨!");
            
            try {
                this.wait();
            } catch (InterruptedException e) {
            }
        }
        
        System.out.println(Thread.currentThread().getName() + " : " + --product);
        this.notifyAll();
    }
}

//生產者
class Productor implements Runnable{
    private Clerk clerk;

    public Productor(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
            }
            
            clerk.get();
        }
    }
}

//消費者
class Consumer implements Runnable{
    private Clerk clerk;

    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            clerk.sale();
        }
    }
}*/
相關文章
相關標籤/搜索