[英]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.