黑马程序员技术交流社区

标题: 基础学习day12多线程2消费者生产者 [打印本页]

作者: 不怕黑人    时间: 2015-7-22 22:17
标题: 基础学习day12多线程2消费者生产者
  1. public class Day12Test1 {

  2.         public static void main(String[] args) {

  3.                 Resouce r = new Resouce();
  4.                 new Thread(new Producer(r)).start();
  5.                 new Thread(new Producer(r)).start();
  6.                 new Thread(new Consumer(r)).start();
  7.                 new Thread(new Consumer(r)).start();
  8.         }

  9. }

  10. class Resouce{
  11.        
  12.         private String name;
  13.         private int count = 1;
  14.         private boolean flag = false;
  15.         public synchronized void set(String name){
  16.                
  17.                 while(flag)
  18.                         try{
  19.                                 wait();
  20.                         }
  21.                         catch(Exception e){
  22. //                                throw new RuntimeException();
  23.                         }
  24.                         this.name = name + count++;
  25.                         System.out.println(Thread.currentThread().getName()+"...生产者......"+this.name);
  26.                         flag = true;
  27.                         notifyAll();
  28.         }
  29.         public synchronized void out(){
  30.                 while(!flag)
  31.                         try{
  32.                                 wait();
  33.                         }
  34.                         catch(Exception e){
  35. //                                throw new RuntimeException();
  36.                         }
  37.                         System.out.println(Thread.currentThread().getName()+"+消费者+"+this.name);
  38.                         flag = false;
  39.                         notifyAll();
  40.         }
  41. }
  42. class Producer implements Runnable{
  43.         private Resouce r;
  44.         Producer(Resouce r){
  45.                 this.r = r;
  46.         }
  47.         public void run(){
  48.                 while(true){
  49.                         r.set("汉堡");
  50.                 }
  51.         }
  52. }
  53. class Consumer implements Runnable{
  54.         private Resouce r;
  55.         Consumer(Resouce r){
  56.                 this.r = r;
  57.         }
  58.         public void run(){
  59.                 while(true){
  60.                         r.out();
  61.                 }
  62.         }
  63. }
复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2