首页 > 代码库 > JAVA中的多线程(六)
JAVA中的多线程(六)
生产者消费者
1 class Resource 2 { 3 private String name; 4 private int count = 1; 5 private boolean flag = false; 6 7 public synchronized void set(String name) 8 { 9 while(flag) 10 try{this.wait();}catch(Exception e){} 11 this.name = name+"--"+count++; 12 System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name); 13 flag = true; 14 this.notifyAll(); 15 } 16 17 public synchronized void out() 18 { 19 while(!flag) 20 try{this.wait();}catch(Exception e){} 21 System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name); 22 flag = false; 23 this.notifyAll(); 24 } 25 } 26 27 class Producer implements Runnable 28 { 29 private Resource res; 30 31 Producer(Resource res) 32 { 33 this.res = res; 34 } 35 36 public void run() 37 { 38 while(true) 39 { 40 res.set("+TT+"); 41 } 42 } 43 } 44 45 class Customer implements Runnable 46 { 47 private Resource res; 48 49 Customer(Resource res) 50 { 51 this.res = res; 52 } 53 54 public void run() 55 { 56 while(true) 57 { 58 res.out(); 59 } 60 } 61 } 62 class ProducerCustomerDemo 63 { 64 public static void main(String[] args) 65 { 66 Resource r = new Resource(); 67 68 Producer pro = new Producer(r); 69 Customer con = new Customer(r); 70 71 Thread t1 = new Thread(pro); 72 Thread t2 = new Thread(con); 73 74 t1.start(); 75 t2.start(); 76 } 77 }
JAVA中的多线程(六)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。