package javaapplication2;
/**
*生产者消费者问提
* 为使达到生产一个消费一个的目的,使用等待唤醒机制
* wait():该方法可以让线程处于冻结状态,并将线程存储到线程池中
* notify():唤醒指定线程池中的任意一个线程
* notifyAll():唤醒指定线程池中的所有线程
* 这些方法必须使用在同步中,因为它们用来操作同步锁上的线程状态
* 在使用这些方法时,必须标识它们所属的锁,标识方式就是 锁对象.wait() 锁对象.notify() 锁对象.notifyAll()
* 相同锁的notify(),可以获取相同锁的wait();
* @author tf
*/
class Res
{
private String name;
private int count;
private boolean flag;
public synchronized void set(String name)
{
if(flag)
try{ wait();}catch (InterruptedException e){}
this.name=name+"--"+count;
count++;
System.out.println(Thread.currentThread().getName()+"....生产者...."+this.name);
flag=true;
notify();
}
public synchronized void get()
{
if(!flag)
try{ wait();}catch (InterruptedException e){}
System.out.println(Thread.currentThread().getName()+"....消费者...."+this.name);
flag=false;
notify();
}
}
class Producer implements Runnable
{
private Res r;
Producer (Res r)
{
this.r=r;
}
public void run()
{
r.set("面包");
}
}
class Consumer implements Runnable
{
private Res r;
Consumer(Res r)
{
this.r =r;
}
public void run()
{
r.get();
}
}
public class JavaApplication2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Res r=new Res();
Producer pro=new Producer(r);
Consumer con=new Consumer(r);
Thread t1=new Thread(pro);
Thread t2=new Thread(con);
t1.start();
t2.start();
}
}