从同步方法中调用方法
我面临一个奇怪的问题,这让我想知道同步方法中到底发生了什么。假设有一个方法
synchronized public void example(){
//...code
int i=call(); //calling another method
//...do something with i
}
,现在在执行call()方法时,另一个对象可以进入这个同步的example()方法吗?那么当call()返回时,可能会出现一些ConcurrentModificationException?怎样做才能避免出现问题?
I'm facing a strange problem which has made me wonder what exactly happens in a synchronized method. Let's say there is a method
synchronized public void example(){
//...code
int i=call(); //calling another method
//...do something with i
}
Now while the call() method is being executed, can another object enter this synchronized example() method? So when the call() returns, there might be some ConcurrentModificationException? What to do in order to avoid problems?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,不能。同步方法基本上与以下相同:
No it can't. A synchronized method is basically the same as:
请注意,在此示例中,如果
call()
不是私有的或者是从类中的其他位置调用的,则其他人可以中断您认为的完全同步过程。如果您期望“a 所做的一切都由synchronized 保护”,那么如果 b 有任何副作用,那么如果
synchronized void a
之外的方法调用b< /代码>。
Note that in this example, if
call()
isn't private or is called from somewhere else in the class, someone else can interrupt what you think is an entirely synchronous process.If you expect "everything that a does to be guarded by synchronized", then if b has any side-effects at all, that guarantee is lost if methods other than
synchronized void a
callb
.当线程进入 Synchronized 方法时,会发生锁定,直到该方法返回(即在调用
call()
之后),锁定才会释放。这是一篇关于锁和同步的好文章:
http://download.oracle.com/javase/tutorial/essential/concurrency /locksync.html
When a thread enters a Synchronized method a lock occurs, the lock doesn't release until that method returns, which would be after your call to
call()
.Here is a good article on locks and synchronization:
http://download.oracle.com/javase/tutorial/essential/concurrency/locksync.html