java多線程

生產者與消費者問題

package xianPack;

//生產者    消費者
public class Test10 {

    public static void main(String[] args) {
        
        final Apple apple = new Apple();
        
        //吃蘋果的人      (上下兩種方法一樣)
        new Thread(new Runnable() {
            public void run() {
                try {
                    apple.eat();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        },"線程1").start();
        
        Thread thread1 = new Thread(new Runnable() {
            public void run() {
                try {
                    apple.eat();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        },"線程2");
        thread1.start();
        
        //種蘋果的
        new Thread(new Runnable() {
            public void run() {
                try {
                    apple.plant();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        },"線程3").start();
        
        new Thread(new Runnable() {
            public void run() {
                try {
                    apple.plant();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"線程4").start();
        
    }
}

class Apple {
    
    int num = 0;   //蘋果的數量
    
    //吃蘋果
    void eat() throws InterruptedException {
        while (true) {
            synchronized (this) {
                if (num > 0) {
                    num--;
                    Thread thread = Thread.currentThread();
                    System.out.println(thread.getName() + "吃蘋果,剩下" + num);
                    //并且通知種蘋果的種
                    notifyAll(); 
                }else {   //沒有蘋果了
                    //進入等待狀態
                    wait();
                    //并且通知種蘋果的種
                    //notify();    //通知一個
                }
            }
            
        }
    }
    
    //種蘋果
    void plant() throws InterruptedException {
        while (true) {
            //鎖放在里邊  一邊吃一邊種
            synchronized (this) {
                //如果生產大于20個,停止生產
                if (num < 20) { 
                    this.num++;
                    Thread thread = Thread.currentThread();
                    System.err.println(thread.getName() + "種蘋果,剩下" + num);
                    
                    //通知吃蘋果的吃
                    notifyAll();    //通知所有的
                }else {     //蘋果太多  不能生產了
                    //等待
                    wait();
                }
            }
            
        }
    }
    
    
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容