我的代码抛出java.lang.IllegalMonitorStateException

时间:2015-04-03 01:07:51

标签: java multithreading

package threads;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public class text implements Runnable {
    static Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {

        testts();
        new Thread(new text()).start();

    }

    static void testts() {
        lock.lock();
    }

    @Override
    public void run() {
        lock.unlock();

        System.out.println("un-locked");
    }
}

引发

Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
    at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:127)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1175)
    at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:431)
    at threads.text.run(text.java:28)
    at java.lang.Thread.run(Thread.java:619)

1 个答案:

答案 0 :(得分:2)

javadoc of ReentrantLock#unlock()

  

如果当前线程不是此锁的持有者那么   IllegalMonitorStateException被抛出。

您的新主题没有锁,主线程没有。因此,当新线程试图解锁它没有保持的锁时,会抛出异常。