hongsenBabe 2020-10-13 14:38 采纳率: 0%
浏览 36

多线程简单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();

}

}

报错内容
图片说明

  • 写回答

1条回答 默认 最新

  • mengtianning 2020-10-13 17:00
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥15 图像超分real-esrgan网络自己训练模型遇到问题
  • ¥15 如何构建全国统一的物流管理平台?
  • ¥100 ijkplayer使用AndroidStudio/CMake编译,如何支持 rtsp 直播流?
  • ¥15 用js遍历数据并对非空元素添加css样式
  • ¥15 使用autodl云训练,希望有直接运行的代码(关键词-数据集)
  • ¥50 python写segy数据出错
  • ¥20 关于线性结构的问题:希望能从头到尾完整地帮我改一下,困扰我很久了
  • ¥30 3D多模态医疗数据集-视觉问答
  • ¥20 设计一个二极管稳压值检测电路
  • ¥15 内网办公电脑进行向日葵