帮忙看一下,为什么有的地方,结果也打印出来了是先消费后生产呢,谢谢!
class Queue
{
boolean available = false;
int value;
public synchronized void setValue(int value)
{
if (!available)
{
this.value = value;
available = true;
notify();
}
//数据还没有取走则等待
try
{
wait();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public synchronized int getValue()
{
if (!available)//没有准备好就等待
{
try
{
wait();
}
catch (Exception e)
{
e.printStackTrace();
}
}
//准备好了数据返回该数据
available = false;
notify();
return value;
}
}
class producer extends Thread
{
Queue q;
producer(Queue q)
{
this .q= q ;
}
public void run ()
{
for (int i = 0; i<10; i++)//共放了十个数据
{
q.setValue(i);
System.out.println("producer:"+i);
}
}
}
class consumer extends Thread
{
Queue q ;
consumer(Queue q)
{
this.q = q;
}
public void run ()
{
while (true )
{
System.out.println("consumer:"+q.getValue());
}
}
}
public class sychronizedThread
{
public static void main(String[] args)
{
Queue q = new Queue();
producer pro = new producer(q); //实例化两个线程
consumer con = new consumer(q);
pro.start();
con.start();
}
}