消息队列:生产消费者模型
1.package com.test;
2.
3.public class Customer implements Runnable {
4. private final Queue<String> queue;
5. public Customer(final Queue<String> queue){
6. this.queue =queue;
7. }
8. @Override
9. public void run() {
10. int i=0;
11. while(true) {
12. try {
13. Thread.sleep(1000);
14. } catch (InterruptedException e) {
15. // TODO Auto-generated catch block
16. e.printStackTrace();
17. }
18. System.out.println("消费者消费了"+this.queue.get());
19.
20. }
21. }
22.}
23.package com.test;
24.
25.public class Producer implements Runnable {
26. private final Queue<String> queue;
27. public Producer(final Queue<String> queue){
28. this.queue =queue;
29. }
30. @Override
31. public void run(){
32. int i=0;
33. while(true) {
34. try {
35. Thread.sleep(500);
36. } catch (InterruptedException e) {
37. // TODO Auto-generated catch block
38. e.printStackTrace();
39. }
40. this.queue.add("第"+(++i)+"消息");
41. System.out.println("生产者生产了第"+i+"个消息");
42. }
43. }
44.}
45.package com.test;
46.
47.import java.util.LinkedList;
48.
49.public class Queue<T> {
50. //设计的是队列FIFO,还是栈FILO
51. private LinkedList<T> queue=new LinkedList<T>();
52. private int min;
53. private int max;
54. private final static int QUEUE_SIZE_DEFAULT_MAX=10;
55. public Queue() {
56. this(QUEUE_SIZE_DEFAULT_MAX);
57. }
58. public Queue(int maxSize) {
59. this.max=maxSize;
60. }
61. //往队列当中放数据
62. public synchronized void add(T t) {
63. //当消息满的时候,进入等待
64. while(this.queue.size() ==this.max) {
65. try {
66. System.out.println("消息已满,开始等待");
67. this.wait(); //等待是释放锁的
68. } catch (InterruptedException e) {
69. // TODO Auto-generated catch block
70. e.printStackTrace();
71. }
72. }
73. this.queue.addLast(t);
74. this.notifyAll(); // 队列不再空的时候,唤醒所有线程
75. }
76. // 往队列当中取数据
77. public synchronized T get() {
78. //当消息为空的时候,进入等待
79. while(this.queue.size() ==0) { //改成while,保证被唤醒后,再来判断一次
80. try {
81. System.out.println("消息为空,开始等待");
82. this.wait(); //等待是释放锁的,被唤醒后,重新持锁,会从该从继续执行
83. } catch (InterruptedException e) {
84. // TODO Auto-generated catch block
85. e.printStackTrace();
86. }
87. }
88. T t=this.queue.getFirst();
89. // 取用后的消息,不应当在存在与队列当中
90. this.queue.removeLast();
91. this.notifyAll(); //队列不再满的时候,唤醒所有线程
92. return t;
93. }
94.}
95.package com.test;
96.
97.public class Test {
98. public static void main(String[] args) {
99. Queue<String> q=new Queue<String>();
100. Thread c1=new Thread(new Customer(q));
101. c1.start();
102. Thread c2=new Thread(new Customer(q));
103. c2.start();
104. Thread p1=new Thread(new Producer(q));
105. p1.start();
106. }
107.}
将一些对象放入“池”中,然后交给池托管这些对象的执行方式,作为使用者,不需要再去关心如何管理这些对象
线程池管理的是线程
类似join,是让线程串行执行
可变尺寸线程池的执行,是全部并发
是在其被加入到池当中以后,立即开始计时