线程同步示例

来源:互联网 发布:sql没有商业智能项目 编辑:程序博客网 时间:2024/05/22 08:09

描述:父亲和儿子共享一个盘子,父亲放苹果,儿子吃苹果,盘子里面只能放一个,父亲放苹果的时候,儿子不能吃,儿子取的时候,父亲不能放,盘子只放一个苹果,完成两个线程的同步问题
注: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();    }}
原创粉丝点击