[英]multithreading in java,difficulty in wait
这是我的代码的一部分,我在使用wait()
时遇到问题
class Leader extends Thread {
private Table table;
synchronized public void run()
{
while(true)
{
try
{
while(table.getResources()!=0)
wait();
table.putResources(5); // here I am updating the value(I have a table class)
} catch(InterruptedException e) { }
}
}
}
class Soldier extends Thread {
public void run()
{
while(true)
{
try
{
synchronized(this)
{
if(table.getResources()==this.need_Value) //checking value of resource
{
sleep(1000);
table.clearResources(); //this will put the value of resource to 0
notifyAll();
}
}
} catch(InterruptedException e) { }
}
}
}
所以基本上我有一个领导者类的线程和一个领导者类的线程。 最初资源为0
因此在Soldier类中资源被更新为5
。 现在假设对于Soldier
类Need_Value为5
,那么它将资源值更新为0
。 因此,现在Leader
类应该在资源为0
再次运行,但实际上它仍在等待。 那么我的wait()
有什么问题吗?
PS-假设我有Table类以及使用的所有构造函数和变量。 我已经省略了它们,因为代码太长
您notify
了另一个对象,而不是wait
。
Leader
类this
同步( this
是因为您将同步放在实例方法上)。 因此,您的Leader
等待Leader
实例被通知。
在您的Soldier
类中,您还将与this
同步,并通知该Soldier
实例。
但是,由于您是在Soldier
实例上进行通知的,而Leader
在Leader
实例上等待,因此不会收到通知。
Soldier
和Leader
这两个实例应使用相同的同步对象。
您可能想通过使用Leader
实例作为Soldier
同步对象来解决此问题
class Soldier extends Thread {
private Leader leader;
public Soldier(Leader leader) {
this.leader = leader;
}
public void run()
{
while(true)
{
try
{
synchronized(leader)
{
if(table.getResources()==this.need_Value) //checking value of resource
{
sleep(1000);
table.clearResources(); //this will put the value of resource to 0
leader. notifyAll();
}
}
} catch(InterruptedException e) { }
}
}
}
阅读此问题的答案: 如何在Java中使用等待和通知? 它详细说明了如何正确使用Wait()和Notify()函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.