对于生产者消费者问题的解决办法中,因为synchronized 的意思是同步的,所以我老是一厢情愿地认为synchronized 解决的是多线程对共享资源的同步问题,据此推理wait(),notify()解决的就是互斥问题了;但是怎么看怎么觉得别扭,今天终于发现,原来synchronized 解决的是互斥,wait(),notify()解决的是同步,这样再看生产者消费者的代码就舒服多了:
class Test
{
public static void main(String[] args)
{
Queue q=new Queue();
Producer p=new Producer(q);
Consumer c=new Consumer(q);
p.start();
c.start();
}
}
class Producer extends Thread
{
Queue q;
Producer(Queue q)
{
this.q=q;
}
public void run()
{
for(int i=0;i<10;i++)
{
q.put(i);
System.out.println("Producer put "+i);
}
}
}
class Consumer extends Thread
{
Queue q;
Consumer(Queue q)
{
this.q=q;
}
public void run()
{
while(true)
{
System.out.println("Consumer get "+q.get());
}
}
}
class Queue
{
int value;
boolean bFull=false;
public synchronized void put(int i)
{
if(!bFull)
{
value=i;
bFull=true;
notify();
}
try
{
wait();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public synchronized int get()
{
if(!bFull)
{
try
{
wait();
}
catch(Exception e)
{
e.printStackTrace();
}
}
bFull=false;
notify();
return value;
}
}