生产者消费者:等待唤醒机制(最终版代码)

来源:互联网 发布:淘宝9.9包邮网 编辑:程序博客网 时间:2024/05/17 06:05

public classStudent {

   private Stringname;

   private int age;

   private boolean flag; // 默认情况是没有数据,如果是true,说明有数据

 

   public synchronized void set(String name,int age) {

      // 如果有数据,就等待

      if (this.flag) {

         try {

            this.wait();

         }catch(InterruptedException e) {

            e.printStackTrace();

         }

      }

 

      // 设置数据

      this.name = name;

      this.age = age;

 

      // 修改标记

      this.flag =true;

      this.notify();

   }

 

   public synchronized void get() {

      // 如果没有数据,就等待

      if (!this.flag) {

         try {

            this.wait();

         }catch(InterruptedException e) {

            e.printStackTrace();

         }

      }

 

      // 获取数据

      System.out.println(this.name +"---" + this.age);

 

      // 修改标记

      this.flag =false;

      this.notify();

   }

}

 

public classSetThread implementsRunnable {

 

   private Students;

   private int x = 0;

 

   public SetThread(Student s) {

      this.s = s;

   }

 

   @Override

   public void run() {

      while (true) {

         if (x % 2 == 0) {

            s.set("林青霞", 27);

         }else{

            s.set("刘意", 30);

         }

         x++;

      }

   }

}

public classGetThread implementsRunnable {

   private Students;

 

   public GetThread(Students) {

      this.s = s;

   }

 

   @Override

   public void run() {

      while (true) {

         s.get();

      }

   }

}

 

/**

 * 最终版代码中:

 *    Student的成员变量给私有的了。

 *    把设置和获取的操作给封装成了功能,并加了同步。

 *    设置或者获取的线程里面只需要调用方法即可。

 */

public classStudentDemo {

   public static void main(String[] args) {

      //创建资源

      Students = newStudent();

     

      //设置和获取的类

      SetThreadst = newSetThread(s);

      GetThreadgt = newGetThread(s);

 

      //线程类

      Threadt1 = newThread(st);

      Threadt2 = newThread(gt);

 

      //启动线程

      t1.start();

      t2.start();

   }

}

0 0
原创粉丝点击