[英]using a queue with threads in simple java program
我只是想知道我是否可以在一些代碼上獲得一些建議
好的,所以我有一個線程化類(非常基礎),基本上會調用此對象,而我的代碼現在才顯示...此代碼給了我無限的wait(),我不知道為什么。
public void play()
{
if(!queue.isEmpty()){
synchronized(this)
{
if(queue.peek().ballCount <=AvailableGolfBalls)
{
//check if there all people in queue, if yes, give them preferance
queue.poll().notify();
}
}
}
hasBalls=false;
try
{
while (!hasBalls)
{
if(AvailableGolfBalls >= count)
{
AvailableGolfBalls -=count;
synchronized(this){
//the main code for thread
}
hasBalls=true;
}
else
{
//there isnt enough balls,wait
queue.add(this);
Thread.sleep(500);
System.out.println(ThreadID.get() +" -no balls availiable ");
synchronized(this)
{
this.wait();
}
}
}
}
catch (InterruptedException exception)
{
}
AvailableGolfBalls +=count;
}
我盡可能地簡化了我的代碼,盡管它是一個非常簡單的程序,但是一周前我才剛開始使用多線程,但是很多概念仍然讓我感到困惑。 該程序的作用本質上是每個線程在運行之前都需要一定數量的球,如果沒有所需的球,請在其可用之前排隊。
在正確的對象上同步時,您沒有調用notify。
您正在this
進行同步,並在隊列中存儲的對象上調用notify
。 您必須對存儲在隊列中的對象進行同步,以正確調用它們的notify
。
Object obj = null;
synchronized(this)
{
if(queue.peek().ballCount <=AvailableGolfBalls)
{
//check if there all people in queue, if yes, give them preferance
obj = queue.poll();
}
}
if(obj!=null){
synchronized(obj){
obj.notify();
}
}
我認為這是錯誤的。 您的代碼非常混亂,因為我們不知道this
是什么類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.