将synchronized() 与ReentrantLock.lock() 混合使用
在 Java 中,ReentrantLock.lock()
和 ReetrantLock.unlock()
使用与 synchronized()
相同的锁定机制吗?
我的猜测是“不”,但我希望我是错的。
示例:
假设线程 1 和线程 2 都可以访问:
ReentrantLock lock = new ReentrantLock();
线程 1 运行:
synchronized (lock) {
// blah
}
线程 2 运行:
lock.lock();
try {
// blah
}
finally {
lock.unlock();
}
假设线程 1 首先到达其部分,然后线程 2 在线程 1 完成之前到达:线程 2 是否会等待线程 1 离开 < code>synchronized() 块,还是会继续运行?
In Java, do ReentrantLock.lock()
and ReetrantLock.unlock()
use the same locking mechanism as synchronized()
?
My guess is "No," but I'm hoping to be wrong.
Example:
Imagine that Thread 1 and Thread 2 both have access to:
ReentrantLock lock = new ReentrantLock();
Thread 1 runs:
synchronized (lock) {
// blah
}
Thread 2 runs:
lock.lock();
try {
// blah
}
finally {
lock.unlock();
}
Assume Thread 1 reaches its part first, then Thread 2 before Thread 1 is finished: will Thread 2 wait for Thread 1 to leave the synchronized()
block, or will it go ahead and run?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,即使线程 1 在同一个
锁上
同步
,线程 2 也可以lock()
。这是文档的内容不得不说:No, Thread 2 can
lock()
even when Thread 1 issynchronized
on the samelock
. This is what the documentation has to say:两种机制不同。实现/性能方面:
在某些情况下,显式锁可以表现得更好。如果您查看我在 Java 5 下执行的锁定机制比较,您会看到在该特定测试(多个线程访问数组)中,以“不公平”模式配置的显式锁定类(黄色和青色三角形)比普通同步(紫色箭头)允许更高的吞吐量。
(我还应该说,synchronized 的性能在最新版本的 Hotspot 中得到了改进;在最新版本或其他情况下可能没有太多改进 - 这显然是一种环境下的测试。)
功能 -明智的:
The two mechanisms are different. Implementation/performance wise:
Under some circumstances, the explicit locks can perform better. If you look at this comparison of locking mechanisms I performed under Java 5, you'll see that in that particular test (multiple threads accessing an array), explicit lock classes configured in "unfair" mode (the yellow and cyan triangles) allow more throughput than plain synchronized (the purple arrows).
(I should also say that the performance of synchronized has been improved in more recent versions of Hotspot; there may not be much in it on the latest versions or indeed under other circumstances-- this is obviously one test in one environment.)
Functionality-wise:
为什么在 Account 类中将余额设为静态?
消除静电,它应该可以工作。
另外,对您的线程使用有疑问。在 TestMain 中,您创建新线程并分配可运行对象,例如 WithdrawRequests &存款请求。但您再次在这些可运行对象的构造函数中创建新线程。这会导致run方法被执行两次!
Why did you make the balance static in Account class?
Remove static and it should work.
Also, have a question about your thread usage. In your TestMain you create new threads and assign runnables like WithdrawRequests & DepositRequests. But again you create new threads inside the constructors of those runnables. This will cause the run method to be executed twice!