美文网首页
java报错java.lang.IllegalMonitorSt

java报错java.lang.IllegalMonitorSt

作者: 尘埃里的玄 | 来源:发表于2020-11-01 13:48 被阅读0次

先把错误的代码放出来,很简单的错误!哈哈哈

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class RedisTest {
    private static Integer inventory = 1001;
    private static final int NUM = 1000;
    private static LinkedBlockingDeque linkedBlockingDeque = new LinkedBlockingDeque();
    static ReentrantLock reentrantLock = new ReentrantLock();
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(inventory,inventory,10L,TimeUnit.SECONDS,linkedBlockingDeque);
        final CountDownLatch countDownLatch = new CountDownLatch(NUM);
        long start = System.currentTimeMillis();
        for (int i = 0;i <= NUM;i++){
            threadPoolExecutor.execute(new Runnable() {
                @Override
                public void run() {
//                    reentrantLock.lock();
                    inventory--;
                    reentrantLock.unlock();
                    System.out.println("线程执行"+Thread.currentThread().getName());
                    countDownLatch.countDown();
                }
            });
        }
        threadPoolExecutor.shutdown();
        try {
            countDownLatch.await();
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("执行线程数"+NUM +"  总耗时:"+(end -start)+"   库存数为"+inventory);

    }
}

出现java.lang.IllegalMonitorStateException错误,由以下情况导致:
1>当前线程不含有当前对象的锁资源的时候,调用obj.wait()方法;
2>当前线程不含有当前对象的锁资源的时候,调用obj.notify()方法。
3>当前线程不含有当前对象的锁资源的时候,调用obj.notifyAll()方法。

相关文章

网友评论

      本文标题:java报错java.lang.IllegalMonitorSt

      本文链接:https://www.haomeiwen.com/subject/zkvyvktx.html