我只是想知道是否可以获得一些关于某些代码的建议
好吧,所以我有一个线程类(非常基本)基本上调用这个对象,我现在将显示其代码...这段代码给了我无限的 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;
}
我尽可能地简化了我的代码,虽然它是一个非常简单的程序,但我一周前才开始使用多线程,很多概念仍然让我感到困惑。 这个程序的作用本质上是每个线程都需要一定数量的球才能运行,如果没有所需的球,则排队直到可用。
最佳答案
在正确的对象上同步时,您没有调用通知。
您正在同步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
是什么类型。
关于java - 在简单的java程序中使用带有线程的队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18174544/