本文介绍了不同线程中的并发(ReentrantLock)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在不同的线程中使用ReentrantLock.有可能吗?P.S.在secondMethod中,"lock.unlock()"抛出IllegalMonitorStateException.

I need to use ReentrantLock in different threads. Does it possible?P.S. In secondMethod "lock.unlock()" throw IllegalMonitorStateException.

public class SomeClass {
    private static ConcurrentHashMap<String, String> hashMap = new ConcurrentHashMap<>();
    private final Lock lock = new ReentrantLock();

    public void firstMethod(Action action) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //SOME CODE BEFORE LOCK
                lock.lock();
                //SOME CODE AFTER UNLOCK
            }
        }).start();
    }

    public void secondMethod(Action action) {
        if (hashMap.get("key").length() == 3)
            lock.unlock();
    }
}

使用java.util.concurrent.locks.Condition解决!

Solved with java.util.concurrent.locks.Condition!

推荐答案

由于所有锁结构均应由不同的线程调用,因此肯定有可能.

It's surely possible because all lock structure are meant to be called by different threads.

您在第二个线程中出错,因为您的方法未在释放之前通过调用lock.lock()来锁定Lock对象;因此,您的线程在解锁之前并不拥有该锁,这是不允许的.

You got error in second threads because your method didn't lock the Lock object by calling lock.lock() before releasing; thus your thread doesn't own the lock before unlocking it, which is not allowed.

这篇关于不同线程中的并发(ReentrantLock)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 19:08