使用CountDownLatch的问题

来源:12-6 重排序1

努力努力再努力QAQ

2020-07-11

在使用CountDownLatch的时候报Exception in thread “Thread-0” java.lang.IllegalMonitorStateException异常
public class Gh {
private static int a = 0, b = 0;
private static int x = 0,y = 0;

public static void main(String[] args) throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    Thread thread1 = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                latch.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            a = 1;
            x = b;
        }
    });

    Thread thread2 = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            b = 1;
            y = a;
        }
    });

    thread1.start();
    thread2.start();
    latch.countDown();
    thread1.join();
    thread2.join();
    System.out.println(x+","+y);
}
写回答

1回答

努力努力再努力QAQ

提问者

2020-07-12

老师我已经解决了,是one线程那里应该也要用latch.await,但是老师你重排序的三种情况的视频当时写代码的时候应该是写错了,把one线程调用了latch.wait,然后运行时候wait已经被老师改回了await,但是视频中没有把wait改回await的过程就导致我运行程序时有异常然后产生了疑惑呜呜。

0
0

线程八大核心+Java并发原理及企业级并发解决方案

完整的并发知识网络+丰富的工作内容分享+50余道并发高频面试题

2512 学习 · 939 问题

查看课程