经典的生产者消费者程序,多线程,解决互斥问题,代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
package com.test; public class ProducerConsumer { public static void main(String[] args) { SynStack ss = new SynStack(); Producer p = new Producer(ss); Consumer c = new Consumer(ss); Thread t = new Thread(p); t.start(); Thread t2 = new Thread(c); t2.start(); } } //定义一个窝头类 class WoTou { int id; WoTou( int id) { this.id = id; } public String toString() { return "WoTou :" +id; } } //定义篓子类用 来放窝头 class SynStack { WoTou[] ss = new WoTou[8]; int index =0; public synchronized void push(WoTou wt) { while(index==ss.length) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notify(); ss[index]=wt; index+ +; } public synchronized WoTou pull() { while(index==0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notify(); index--; return ss[index]; } } //定义生 产者类 class Producer implements Runnable { SynStack ss = null; public Producer(SynStack ss) { this.ss = ss; } public void run() { for(int i=0;i<20;i++) { WoTou wt = new WoTou(i); ss.push(wt); System.out.println( "生产了"+wt); try { Thread.sleep((long) (Math.random()*100)); } catch (InterruptedException e) { e.printStackTrace(); } } } } class Consumer implements Runnable { SynStack ss = null; public Consumer(SynStack ss) { this.ss = ss; } public void run() { for(i nt i=0;i<20;i++) { WoTou wt = ss.pull(); System.out.println( "消费了"+wt); try { Thread.sleep( (long) (Math.random()*1000)); } catch (InterruptedException e) { e.printStackTrace(); } } } } |
运行结果: