首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Java相关 >

黑马软件工程师_——多线程

2013-07-09 
黑马程序员_——多线程------- a hrefhttp://www.itheima.com targetblankandroid培训/a、a href

黑马程序员_——多线程
------- <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


//实现runnable接口,覆盖run方法,建立一个thread类对象,
//将runnable接口子类对象作为实际参数传递给thread。调用threadstart方法。
{
 private resource res;
 consumer(resource res)
 {
  this.res=res;
 }
 public void run()
 {
  while(true)
  {
   res.out("");
  }
 }
} 多线程
[解决办法]
好     好

热点排行