線程同步示例

描述:父親和兒子共享一個盤子,父親放蘋果,兒子吃蘋果,盤子裏面只能放一個,父親放蘋果的時候,兒子不能吃,兒子取的時候,父親不能放,盤子只放一個蘋果,完成兩個線程的同步問題
注:synchronized修飾的非靜態方法是對象鎖,靜態方法是類鎖

//盤子
class Dish{
    int apple =0;
    public synchronized void add() throws Exception{

        while(apple==1){
            this.wait();
        }
        if(apple==0){
            System.out.println("putting");
            apple=1;
            Thread.sleep(1000);
        }
        this.notify();
    }

    public synchronized void reduce()throws Exception{

        while(apple == 0){

            this.wait();
        }
        if(apple == 1){
            System.out.println("eatting");
            apple=0;
            this.notify();
        }
    }
}

class Father extends Thread{

    private Dish dish;

    public Father(Dish dish){
        this.dish = dish;
    }

    public void run(){
        while(true){
            try {
                dish.add();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

class Son extends Thread{

    private Dish dish;

    public Son(Dish dish){
        this.dish = dish;
    }

    public void run(){
        while(true){
            try {
                dish.reduce();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
public class apple {

    public static void main(String[] args) {
        Dish dish = new Dish();
        Father father = new Father(dish);
        Son son = new Son(dish);
        father.start();
        son.start();
    }
}
發佈了60 篇原創文章 · 獲贊 14 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章