同一对象的两个不同的同步方法?
我在一个类中有 2 个同步方法,即 method1() 和 method2()。一个线程说“线程 1”通过执行同步 method1() 来持有该类对象的锁。另一个线程说“线程 2”,可以在“线程 1”持有该对象的同时通过 method2() 访问该锁吗?锁。
这种情况类似于具有同步add() 和remove() 方法的java.util.Vector 类。 请也解释一下这个案例。
I have 2 synchronized methods in a class say method1() and method2(). A thread say "Thread 1" holds the lock on that object of the class by executing the synchronized method1().Can another thread say "Thread 2" , access the lock via method2() at the same time while "Thread 1" holding the lock.
This case is analogs to java.util.Vector class having synchronized add() and remove() methods.
Please explain this case too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不会。Java 中的
synchronized
方法与将其主体包装在synchronized (this)
块中的整个方法相同。因此,如果一个线程处于同步方法中,则另一个线程不能同时处于同一对象上的不同同步方法中。这与
Vector
的关系是,您不希望某些代码尝试删除元素,而其他代码则尝试添加元素。这就是临界区的概念;你不仅不希望别人尝试做你正在做的事情,你也不希望别人做一些不同的事情来干扰你。No. A
synchronized
method in Java is identical to the whole method having its body wrapped in asynchronized (this)
block. So if one thread is in asynchronized
method, another thread cannot simultaneously be in a differentsynchronized
method on the same object.The way this relates to a
Vector
is that you don't want some code trying to remove an element while other code is trying to add an element. This is the concept of a critical section; you not only don't want someone else trying to do what you're doing, you also don't want someone else doing something different that would interfere.只要线程 1 持有相同的锁,线程 2 就可以访问该锁,但无法进入该锁所保护的块。
Thread2 can access the lock but can't enter the block guarded by that lock as long as Thread1 is holding the same lock.
不,一次只有一个线程可以持有锁
http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/essential/concurrency/syncmeth.html
No, only one thread can hold the lock at one time
http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/essential/concurrency/syncmeth.html