java 为什么下面的代码会导致不稳定死锁?

pbossiut  于 2023-03-16  发布在  Java
关注(0)|答案(1)|浏览(100)

enter image description here
我想验证synchronized关键字!!但是结果和我预测的不一致!!我不明白为什么会发生死锁

private final ReentrantLock lock = new ReentrantLock(true);
    private int atomicInteger = 0;

    public void writer() {
        dd();
    }

    public void reader() {
        dd();
    }

    public synchronized void dd() {
        atomicInteger++;
    }

    public void test() {
        lock.lock();
        atomicInteger = 0;
        Thread writer = new Thread(this::writer);
        Thread reader = new Thread(this::reader);
        writer.start();
        reader.start();
        for (; ; ) {
            if (atomicInteger == 2) {
                lock.unlock();
                System.out.println(Thread.currentThread().getName()+"Lock released!");
                break;
            }
        }
    }

    @Test
    public void volatileTest() {
        for (int i = 0; i < 100; i++) {
            Thread thread = new Thread(this::test);
            thread.setName("thread【" + i + "】");
            thread.start();
        }
        for (; ; ) {

        }
    }
ogq8wdun

ogq8wdun1#

我使用synchronized来确保atominIntger在被修改时会被更新到主存中!但是它似乎不起作用

相关问题