使用CowntDownLatch测试强制竞争条件会导致java.lang.IllegalMonitorStateException

5 java countdownlatch

我试图创建一个测试,我试图强制一个竞争条件(或至少增加其发生的可能性),我已经使用了CountDownLatch.

问题是我得到了java.lang.IllegalMonitorStateException我的CountDownLatch.wait().我肯定在滥用它CountDownLatch,我肯定不会以聪明的方式创建这个测试.

这个简单的代码再现了我的想法和我的问题(我也有一个要点):

import java.util.*;
import java.util.concurrent.*;

public class Example {

    private static BusinessLogic logic;

    public static void main(String[] args) {
        final Integer NUMBER_OF_PARALLEL_THREADS = 10;
        CountDownLatch latch = new CountDownLatch(NUMBER_OF_PARALLEL_THREADS);
        logic = new BusinessLogic();

        // trying to force the race condition
        List<Thread> threads = new ArrayList<Thread>(NUMBER_OF_PARALLEL_THREADS);
        for (int i=0; i<NUMBER_OF_PARALLEL_THREADS; i++) {
            Thread worker = new Thread(new WorkerRunnable(latch));
            threads.add(worker);
            worker.start();
        }

        for (int i = 1; i <= NUMBER_OF_PARALLEL_THREADS; i++) {
            try {
                threads.get(i).wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Just a dummy business logic class.
     * I want to "force" a race condition at the method doSomething().
     */
    private static class BusinessLogic {
        public void doSomething() {
            System.out.println("Doing something...");
        }
    }

    /**
     * Worker runnable to use in a Thead
     */
    private static class WorkerRunnable implements Runnable {
        private CountDownLatch latch;

        private WorkerRunnable(CountDownLatch latch) {
            this.latch = latch;
        }

        public void run() {
            try {
                // 1st I want to decrement the latch
                latch.countDown();
                // then I want to wait for every other thread to 
                latch.wait(); // the exception is thrown in this line.
                // hopefully increase the probability of a race condition...
                logic.doSomething();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果当前线程不是对象监视器的所有者,则抛出CountDownLatch.wait()状态的javadoc IllegalMonitorStateException.但我担心我不明白这是什么意思,我也无法想象如何重新创建我的代码以避免这种异常.

编辑:通过答案中提供的提示,我已经创建了上述示例的新版本,并且我已经存储在这个要点中.我现在没有任何例外.

hea*_*den 13

试试await(),不是wait().

await()将等到闩锁达到零. wait()与锁存器无关,而不是你想要的WorkerRunnable.但是,仅供参考,为了在wait()不获得异常的情况下进行调用,您必须拥有对象的监视器,并且要成为所有者,您必须处于synchronized该对象的块中.