ReentrantLock中tryLock的使用

microsoftq microsoftq 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
请各位帮忙看看,以下是代码

static ReentrantLock lock = new ReentrantLock();

public static void main(String[] args) {
ExecutorService es = Executors.newCachedThreadPool();

es.execute(new Runnable() {

@Override
public void run() {
foo("thread1");
}
});

es.execute(new Runnable() {

@Override
public void run() {
foo("thread2");
}
});
}

private static void foo(String threadName) {
try {
lock.tryLock();
System.out.println(lock.getHoldCount());
System.out.println(threadName);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} finally {
lock.unlock();
System.out.println(lock.getHoldCount());
}
}

输出信息是:
1
thread1
(此处无等待)
0
thread2
0
Exception in thread "pool-1-thread-2" java.lang.IllegalMonitorStateException
at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:155)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1260)
at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:460)
at test.reentrantlock.Test.foo(Test.java:43)
at test.reentrantlock.Test.access$0(Test.java:31)
at test.reentrantlock.Test$2.run(Test.java:26)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)

为什么线程2会立刻获得锁,而且获得锁之后的HoldCount是0,最后抛出的异常是因为线程1准备释放锁时,它已经不是锁持有者了。
...全文

相关推荐

评论 8
收藏 已收藏
分享
返回顶部
microsoftq
Java SE 62,620 成员 307,251 内容