简体   繁体   English

不同线程中的并发(ReentrantLock)

[英]Concurrency (ReentrantLock) in different threads

I need to use ReentrantLock in different threads. 我需要在不同的线程中使用ReentrantLock。 Does it possible? 有可能吗 PS In secondMethod "lock.unlock()" throw IllegalMonitorStateException. PS在secondMethod“ lock.unlock()”中抛出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();
    }
}

Edit: Solved with java.util.concurrent.locks.Condition! 编辑:解决与java.util.concurrent.locks.Condition!

The thread that locks should also be the thread that unlocks. 锁定的线程也应该是解锁的线程。 Trying to solve it in any other way would result in race conditions. 试图以任何其他方式解决它会导致比赛状况。

It's surely possible because all lock structure are meant to be called by different threads. 这是肯定有可能的,因为所有锁结构都应由不同的线程调用。

You got error in second threads because your method didn't lock the Lock object by calling lock.lock() before releasing; 您在第二个线程中出错,因为您的方法未在释放之前通过调用lock.lock()来锁定Lock对象。 thus your thread doesn't own the lock before unlocking it, which is not allowed. 因此,您的线程在解锁之前并不拥有该锁,这是不允许的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM