简体   繁体   中英

Concurrency (ReentrantLock) in different threads

I need to use ReentrantLock in different threads. Does it possible? PS 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();
    }
}

Edit: Solved with 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; thus your thread doesn't own the lock before unlocking it, which is not allowed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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