要使5个线程协议同步和互斥协调

public static void main(String[] args) {
        Main main = new Main();
//        main.jframe();
//        main.xialakuang();
        put_Peach put_peach = new put_Peach();
        push_peach  push_peach =new push_peach();
        Monkey t1 = new Monkey("father",put_peach);
        Monkey t2 = new Monkey("mother",put_peach);
        Monkey t3 = new Monkey("son_01",push_peach);
        Monkey t4 = new Monkey("son_02",push_peach);
        Monkey t5 = new Monkey("son_03",push_peach);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();

    }
class push_peach extends put_Peach{
    void son_01(){
        -- peachNum;
        System.out.println(Thread.currentThread().getName()+"儿子正在吃桃子,目前盘子的数量为:"+peachNum);
    }
    int get_peach(){
        return  peachNum;
    }
    public synchronized void push_Peach() {
        son_01();
    }
    boolean if_push_peach(){
        return true;
    }
}
class put_Peach {
    static int peachNum = 0;

    public int getPeachNum() {
        return peachNum;
    }
    void father(){
        peachNum ++;
        System.out.println(Thread.currentThread().getName()+"正在放桃子,目前盘子的数量为:"+peachNum);
    }

    public synchronized void getPeach() {
        father();
    }
    boolean if_put_peach(){
        return true;
    }
}

class Monkey extends Thread {
    private put_Peach put_Peach;
    private push_peach push_peach;

    public Monkey(String name, put_Peach put_Peach) {
        super(name);
        this.put_Peach = put_Peach;
    }
    public Monkey(String name, push_peach push_peach) {
        super(name);
        this.push_peach = push_peach;
    }
    public void run() {
        while (true) {
            if(push_peach.if_push_peach()){
                push_peach.getPeach();
                break;
            }else{
                put_Peach.getPeach();
                break;
            }
        }
    }

要使5个线程协议同步和互斥协调。 put用来放桃子(两个线程不能同时放桃子) push用来吃桃子(三个线程不能同时吃桃子,且吃桃子的速度不同)最后结果报错

img

首先你那个father的,构造方法赋值了,其实他是put_peach,对吧,但是push_peach是null, 所以while下面那个if判断就报空指针了