为什么会出java.lang.IllegalMonitorStateException异常?
package threadExam;
import java.util.concurrent.locks.ReentrantLock;
class Thread1 extends Thread {
private ReentrantLock lock1;
private ReentrantLock lock2;
public Thread1(ReentrantLock lock1, ReentrantLock lock2)
{
this.lock1 = lock1;
this.lock2 = lock2;
}
public void run()
{
for (int i = 1; i <=52; i++)
{
System.out.print(i);
if (i % 2 == 0) {
lock1.lock();
lock2.unlock();
}
}
}
}
class Thread2 extends Thread {
private ReentrantLock lock1;
private ReentrantLock lock2;
public Thread2(ReentrantLock lock1, ReentrantLock lock2)
{
this.lock1 = lock1;
this.lock2 = lock2;
}
public void run()
{
for (int i = 0; i < 26; i++)
{
System.out.print((char)(i + 'A'));
lock2.lock();
lock1.unlock();
}
}
}
public class Exam1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ReentrantLock lock1 = new ReentrantLock();
ReentrantLock lock2 = new ReentrantLock();
Thread t1 = new Thread1(lock1, lock2);
Thread t2 = new Thread2(lock1, lock2);
lock2.lock();
t1.run();
t2.run();
}
}
运行后报错提示:
Exception in thread "main" java.lang.IllegalMonitorStateException
at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:151)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1261)
at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:457)
at threadExam.Thread1.run(Exam1.java:30)
at threadExam.Exam1.main(Exam1.java:67)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这段代码全是问题啊!
启动线程应该使用
start
方法,直接调用run
方法不会创建新的线程一个线程只能释放它自己的锁,不能释放别的线程的锁
一个线程调用了n次
lock
,那么它最多也只能调用n次unlock
程序在运行时可能出现如下情况
主线程 lock2.lock
thread1 run 此时 i=1 跳过
thread2 运行 lock2.lock lock1.unlock
还没有lock的情况下就unlock