标签:ati while 分析 over except class span 多线程 current
生产者/消费者问题
分析:
1 package cn.lyog.javase; 2 3 //店员 4 class Clerk { 5 int product; 6 7 public synchronized void addProduct() { 8 if (product >= 20) { 9 try { 10 wait(); 11 } catch (InterruptedException e) { 12 e.printStackTrace(); 13 } 14 } else { 15 product++; 16 System.out.println(Thread.currentThread().getName() + "生产了第" + product + "个产品"); 17 notifyAll(); 18 } 19 } 20 21 public synchronized void ConsumeProduct() { 22 if (product <= 0) { 23 try { 24 wait(); 25 } catch (InterruptedException e) { 26 e.printStackTrace(); 27 } 28 } else { 29 System.out.println(Thread.currentThread().getName() + "消费了第" + product + "个产品"); 30 product--; 31 notifyAll(); 32 } 33 } 34 } 35 36 // 生产者 37 class Productor implements Runnable { 38 Clerk clerk; 39 40 public Productor(Clerk clerk) { 41 super(); 42 this.clerk = clerk; 43 } 44 45 public void run() { 46 while (true) { 47 try { 48 Thread.currentThread(); 49 Thread.sleep(100); 50 } catch (InterruptedException e) { 51 e.printStackTrace(); 52 } 53 clerk.addProduct(); 54 } 55 } 56 57 } 58 59 // 消费者 60 class Consumer implements Runnable { 61 Clerk clerk; 62 63 public Consumer(Clerk clerk) { 64 super(); 65 this.clerk = clerk; 66 } 67 68 @Override 69 public void run() { 70 while (true) { 71 try { 72 Thread.currentThread(); 73 Thread.sleep(60); 74 } catch (InterruptedException e) { 75 e.printStackTrace(); 76 } 77 clerk.ConsumeProduct(); 78 } 79 } 80 } 81 82 public class TestProduceConsume { 83 84 public static void main(String[] args) { 85 Clerk clerk = new Clerk(); 86 Productor pd = new Productor(clerk); 87 Consumer cs = new Consumer(clerk); 88 89 Thread t1 = new Thread(pd); 90 Thread t2 = new Thread(pd); 91 Thread t3 = new Thread(cs); 92 93 t1.setName("生产者1"); 94 t2.setName("生产者2"); 95 t3.setName("消费者1"); 96 97 t1.start(); 98 t2.start(); 99 t3.start(); 100 101 } 102 103 }
标签:ati while 分析 over except class span 多线程 current
原文地址:http://www.cnblogs.com/lyog/p/8016114.html