日期:2014-05-20  浏览次数:20700 次

黑马程序员_——多线程
------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------


class  xiancheng
{
 public static void main(String[] args)
 {
  resource r=new resource();//创建一个新资源
  producer pro=new producer(r);//生产者
  consumer con=new consumer(r);//消费者
  Thread t1= new Thread(pro); //创建4个线程
  Thread t2= new Thread(pro); 
  Thread t3= new Thread(con); 
  Thread t4= new Thread(con); 
  t1.start();//线程开启,运行run方法
  t2.start();
  t3.start();
  t4.start();
 }
}


class resource//资源
{
 private String name;
 private int count=1;//记录商品编号
 private boolean flag=false;
 public synchronized void set(String name)
 {
  while (flag)//循环判断线程是否符合条件
  {
   try
   {
    this.wait();//如果不满足条件,等待。
   }
   catch (Exception e)
   {
   }
  }
  this.name=name+"--"+count++;
 /*获取当前运行线程的名字 +  生产者  +商品编号*/
  System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);
  flag=true;
  this.notifyAll();
 }
 public synchronized void out(String name)
 {
  while (!flag)//循环判断线程是否符合条件
  {
   try
   {
    this.wait();//如果不满足条件,等待。
   }
   catch (Exception e)
   {
   }
  }
 /*获取当前运行线程的名字 +  消费者  +商品编号*/
  System.out.println(Thread.currentThread().getName()+"...消费者......"+this.name);
  flag=false;
  this.notifyAll();//唤醒全部等待的线程
 }
}


class producer implements Runnable//实现runnable接口要覆盖run方法,runnable是
{
 private resource res;
 producer(resource res)
 {
  this.res=res;
 }
 public void run()
 {
  while(true)
  {
   res.set("+商品+");
  }
 }
}


class consumer implements Runnable