多线程简单demo 报错很头疼怎么解决

多线程简单demo

public class Produce {
private Integer max = 10 ;
private Integer capacity = new Integer(0);

public void in(int num){
    synchronized (capacity) {
        while (num+capacity>max){
            System.out.println("in 被阻塞 线程号:"+Thread.currentThread().getName());
            try {
                capacity.wait();
                System.out.println(Thread.currentThread().getState());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("in 激活 线程号:"+Thread.currentThread().getName());
        System.out.println("当前数量:" + capacity +"+"+ num);
        capacity += num;
        System.out.println(Thread.currentThread().getState());
        capacity.notifyAll();
    }
}

public void out(int num){
    synchronized (capacity) {
        while (num>capacity){
            try {
                System.out.println("out 被阻塞 线程号:"+Thread.currentThread().getName());
                capacity.wait();
                System.out.println(Thread.currentThread().getState());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("out 激活 线程号:"+Thread.currentThread().getName());
        System.out.println("当前数量:" + capacity +"-"+ num);
        capacity -= num;
        capacity.notifyAll();
    }
}

public static void main(String[] args) {
    Produce produce = new Produce();

    new Thread(new Runnable() {
        @Override
        public void run() {
            produce.out(5);
        }
    }).start();
    new Thread(new Runnable() {
        @Override
        public void run() {
            produce.out(3);
        }
    }).start();
    new Thread(new Runnable() {
        @Override
        public void run() {
            produce.out(1);
        }
    }).start();


    new Thread(new Runnable() {
        @Override
        public void run() {
            produce.in(5);
        }
    }).start();

    new Thread(new Runnable() {
        @Override
        public void run() {
            produce.in(3);
        }
    }).start();

    new Thread(new Runnable() {
        @Override
        public void run() {
            produce.in(1);
        }
    }).start();

}

}

报错内容
图片说明

因为capacity这个对象一直在变, 线程锁的不是同一个对象,可以这样:private final Object lock = new Object(); synchronized (lock) {