生產者與消費者



public class tt {
    public static void main(String[] args) {
        Q q = new Q();
        new Thread(new Producer(q)).start();
        new Thread(new Customer(q)).start();
    }

}

class Producer implements Runnable{
    Q q;
    public Producer(Q q){this.q = q;}//
    public void run() {
        int i = 0;
        while(true){
            if(i == 0){
                q.put("cup", "for drinking");
            }else{
                q.put("desk", "for study");
            }
            i = (i+1)%2;
        }
    }
   
}

class Customer implements Runnable{
    Q q;
    public Customer(Q q){this.q = q;}
    public void run() {
        while(true){
            q.get();
        }
    }
   
}

class Q{
    String name="unknown";
    String desc="unknown";
    boolean isFull = false;
    public synchronized void put(String name, String desc){
        if(isFull)
            try {
                wait();
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        this.name = name;
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.desc = desc;
        isFull = true;
        notify();
    }
    public synchronized void get(){
        if(!isFull)
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        System.out.print(name);
        System.out.println(":" + desc);
        isFull = false;
        notify();
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章