如何确保java代码段有监视器
因此,我正在编写一个介绍性的 java 程序来习惯多线程,但是,我在使用监视器时遇到了一些问题。特别是,当我进行 primes[0].notifyAll() 调用时,下面的代码部分会抛出 IllegalMonitorStateException 。
Integer[] primes=new Integer[3];
if(primes[0]>0{
{
synchronized(primes[0]){
int returning=primes[0];
primes[0]=0;
primes[0].notifyAll();
return returning;}
}
我对synchronized关键字的理解是,它确保您在进入代码块之前拥有监视器,因此按照这个逻辑,我应该拥有用于notifyAll()调用的监视器。我是否误解了 Java 用于同步的策略,或者我实现该策略的方式是否存在一些错误?
So I'm writing an introductory java program to get used to multithreading, however, I'm having a little bit of trouble with the monitors. In particular, the below code section is throwing an IllegalMonitorStateException when I make the primes[0].notifyAll() call.
Integer[] primes=new Integer[3];
if(primes[0]>0{
{
synchronized(primes[0]){
int returning=primes[0];
primes[0]=0;
primes[0].notifyAll();
return returning;}
}
My understanding of the synchronized keyword was that it ensured that you had the monitor before entering the code block, so by that logic I should have the monitor for the notifyAll() call. Am I misunderstanding the strategy that Java uses for synchronizing or is there some bug in the way I'm implementing that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是您已将一个新对象重新分配给 primes[0]。
上面的语句已经同步了 primes[0] 引用的对象。
上面的语句现在已经将一个新对象重新分配给 primes[0],而不是您拥有锁/监视器的对象。
最后,您尝试在新对象上调用notifyAll(),而不是您锁定的对象,因此会出现异常。
根据您想要实现的目标,以下操作可能会满足您的要求:
The problem is that you have reassigned a new object to primes[0].
The above statement has synchronized on the object referenced by primes[0]
The above statement has now reassigned a new object to primes[0], NOT the one you own a lock/monitor on.
Lastly you're trying to notifyAll() on the new object, not the one you have a lock on, hence the exception.
Depending upon what you're trying to accomplish, the following may do what you want:
我希望你在这里得到空指针异常,因为 primes[0] 尚未分配。
i would expect you get null pointer exceptions here, as primes[0] hasn't been allocated.