基于java多线程来实现生产者和消费者的实例
声明:本实例是在网上看到,做了很小的修改。所以感谢之前的作者。只是一时忘了哪儿看到,没法加入链接,向原作者道歉,以示尊重。抱歉-^)...
同步栈:
1 class SycnStack { 2 private Integer index = 0; 3 private char[] data; 4 5 public SycnStack(int num) { 6 data = new char[num]; 7 } 8 9 public void push(char c) { 10 synchronized (this) {// 对index加锁为何不行???必须this 11 while (index == data.length ) { 12 System.out.println(index +" 池子已满,不能放入!" 13 + Thread.currentThread().toString()); 14 try { 15 this.wait(); 16 } catch (InterruptedException e) { 17 e.printStackTrace(); 18 } 19 } 20 this.notify();// 获取锁 21 data[index] = c; 22 System.out.println(index +" 放入" + c + " " 23 + Thread.currentThread().toString()); 24 index++; 25 } 26 } 27 28 public Character pop() { 29 synchronized (this) { 30 while (index == 0) { 31 System.out.println(index +" 池子已空,取不了了!" 32 + Thread.currentThread().toString()); 33 try { 34 this.wait(); 35 } catch (InterruptedException e) { 36 e.printStackTrace(); 37 } 38 } 39 this.notify(); 40 index--; 41 char c = data[index]; 42 System.out.println(index +" 取出" + c + " " 43 + Thread.currentThread().toString()); 44 return c; 45 } 46 } 47 }
生产者和消费者:
1 class Producer implements Runnable { 2 private SycnStack stack; 3 4 public Producer(SycnStack stack) { 5 this.stack = stack; 6 } 7 8 public void run() { 9 int i = 10; 10 while (i-- > 0) { 11 stack.push((char) (26 * Math.random() + 'A')); 12 Thread.yield(); 13 } 14 } 15 } 16 17 class Consumer implements Runnable { 18 private SycnStack stack; 19 20 public Consumer(SycnStack stack) { 21 this.stack = stack; 22 } 23 24 public void run() { 25 int i = 10; 26 while (i-- > 0) { 27 stack.pop(); 28 Thread.yield(); 29 } 30 } 31 }
主程序:
1 public class ProductorConsumer { 2 public static void main(String[] args) { 3 SycnStack s = new SycnStack(5); 4 new Thread(new Producer(s)).start(); 5 new Thread(new Consumer(s)).start(); 6 } 7 }
That's all. thank you ...