[关闭]
@chenxuxiong 2016-05-23T04:51:16.000000Z 字数 1642 阅读 417

生产者与消费者模式

JAVA基础 设计模式


  1. import java.util.Stack;
  2. public class ProduceAndConsumer {
  3. public static void main(String[] args) {
  4. FactoryStack fs=new FactoryStack();
  5. Producer p1=new Producer(fs,"PA");
  6. Producer p2=new Producer(fs,"PB");
  7. Consumer c1=new Consumer(fs,"CA");
  8. Consumer c2=new Consumer(fs,"CB");
  9. new Thread(p1).start();
  10. new Thread(p2).start();
  11. new Thread(c1).start();
  12. new Thread(c2).start();
  13. }
  14. }
  15. class Car{
  16. int id;
  17. Car(int id ){
  18. this.id=id;
  19. }
  20. public String toString(){
  21. return "Car :" +id;
  22. }
  23. }
  24. class FactoryStack{
  25. private Stack<Car> cars=new Stack<Car>();
  26. public synchronized void push(Car car){
  27. while(cars.size()>=6){
  28. try {
  29. System.out.println("仓库已满,等待消费");
  30. this.wait();
  31. } catch (InterruptedException e) {
  32. }
  33. }
  34. this.notify(); //唤醒等待的线程进行消费
  35. cars.add(car);
  36. }
  37. public synchronized Car pop(){
  38. while(cars.size()==0){
  39. System.out.println("存货不足,等待生产");
  40. try {
  41. this.wait();
  42. } catch (InterruptedException e) {
  43. e.printStackTrace();
  44. }
  45. }
  46. this.notify();
  47. return cars.pop();
  48. }
  49. /*
  50. * int index=0;
  51. * Car[] cars=new Car[6];
  52. * public void push(Car car){
  53. * cars[index]=car;
  54. * }
  55. * public synchronized Car pop(){
  56. * index--;
  57. return cars[index];
  58. }
  59. *
  60. * */
  61. }
  62. class Producer implements Runnable{
  63. private FactoryStack fs=null;
  64. private String name;
  65. Producer(FactoryStack fs,String name){
  66. this.fs=fs;
  67. this.name=name;
  68. }
  69. @Override
  70. public void run() {
  71. for(int i=1;i<20;i++){
  72. Car car=new Car(i);
  73. fs.push(car);
  74. System.out.println(name+" create car "+i);
  75. try {
  76. Thread.sleep(100);
  77. } catch (InterruptedException e) {
  78. e.printStackTrace();
  79. }
  80. }
  81. }
  82. }
  83. class Consumer implements Runnable{
  84. private FactoryStack fs=null;
  85. private String name;
  86. Consumer(FactoryStack fs,String name){
  87. this.fs=fs;
  88. this.name=name;
  89. }
  90. @Override
  91. public void run() {
  92. for(int i=1;i<20;i++){
  93. Car car=fs.pop();
  94. System.out.println(name+" get car "+car.id);
  95. try {
  96. Thread.sleep(1000);
  97. } catch (InterruptedException e) {
  98. e.printStackTrace();
  99. }
  100. }
  101. }
  102. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注