在Java1.5以前的版本中,因为监视器是来自于Object,为了线程的互斥访问,用的synchronized方法或者模块
在synchronized中,“锁”的操作是隐式的,而且每一个锁里只能有一组wait-notify或是wait-notifyAll方法,这样的弊端在于
等待和唤醒的缓冲线程里不仅包括了生产者也包括了消费者,这样就不能指定唤醒进程,要么唤醒了全部进程,影响了效率,要么休眠了所有进程,发生死锁
所以这个只能适用于单生产者单消费者的情况
eg:
class Resource
{
String name;
private int count = 1;
String id;
private boolean flag = false;//初始默认没有产品
public synchronized void producer(String name)
{
if(flag)
try{wait();} catch (InterruptedException ex){}
this.name = name;
id = name+count++;
System.out.println(Thread.currentThread().getName()+"--->生产:"+id);
flag = true;
notify();
}
public synchronized void consumer()
{
if(!flag)
try{wait();} catch (InterruptedException ex){}
System.out.println(Thread.currentThread().getName()+"--------->消费"+id);
flag = false;
notify();
}
}
class Producer implements Runnable
{
Resource r;
Producer(Resource r)
{
this.r = r;
}
public void run()
{
while(true)
{
r.producer("包子");
}
}
}
class Consumer implements Runnable
{
Resource r;
Consumer(Resource r)
{
this.r = r;
}
public void run()
{
while (true)
{
r.consumer();
}
}
}
class ThreadPC
{
public static void main(String[] args)
{
//创建资源
Resource r = new Resource();
//创建线程任务
Producer p = new Producer(r);
Consumer c = new Consumer(r);
//创建线程
Thread tp = new Thread(p);
Thread tc = new Thread(c);
//开启线程
tp.start();
tc.start();
}
}