‘!~淼 2020-09-08 10:27 采纳率: 0%
浏览 154

多线程的lock和condition为什么锁没有被释放

public static void main(String[] args) throws InterruptedException {
//        Producer producer = new Producer();
//        Concumer concumer = new Concumer();
//
//        producer.producer();
//        concumer.foo();
        Lock lock =new ReentrantLock();
        Condition condition = lock.newCondition();

        AtomicInteger count = new AtomicInteger(10);
        ConcurrentHashMap<Object,Object> map = new ConcurrentHashMap<>();

        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lock.lock();
                try {
                    int value = new Random().nextInt();
                    map.put(value,value);
                    condition.signal();
                }finally {
                    lock.unlock();
                }
            }).start();
        }

        lock.lock();
        try {
            while (count.get()>0){
                condition.await();
            }
        }finally {
            lock.unlock();
        }

        System.out.println(map.toString());
    }

为什么这段代码的锁没有被释放一直卡死在那里

  • 写回答

2条回答 默认 最新

  • storm_huang 2020-09-08 11:32
    关注

    因为你的AtomicInteger count = new AtomicInteger(10);没有做递减,count是一直大于0,进入死循环。应该在线程设置map后执行递减。

    try {
                        int value = new Random().nextInt();
                        map.put(value, value);
                        count.decrementAndGet();
                        condition.signal();
                    } finally {
                        lock.unlock();
                    }
    
    评论

报告相同问题?

悬赏问题

  • ¥50 这Mac系统提示虚拟内存不足,怎么解决
  • ¥15 Rs232电路无法收发数据,求帮助
  • ¥15 百度cookie扫码登录器
  • ¥15 微机原理汇编语言debug调试实验
  • ¥23 matlab可以把相图转换为庞加莱映射吗
  • ¥15 Arduino电机和openmv连接异常
  • ¥15 Arcgis河网分级报错
  • ¥200 java+appium2.1+idea
  • ¥20 请帮我做一个EXE的去重TXT文本
  • ¥15 工价表引用工艺路线,应如何制作py和xml文件