1 package threadtest;
2
3 import java.util.LinkedList;
4 import java.util.concurrent.TimeUnit;
5 import java.util.concurrent.atomic.AtomicInteger;
6
7 public class QueueTest01 {
8 private LinkedList<Object> list = new LinkedList<Object>();
9 private AtomicInteger count = new AtomicInteger(0);
10 private final int minSize = 0;
11 private final int maxSize;
12
13 public QueueTest01(int maxsize) {
14 this.maxSize = maxsize;
15 }
16
17 private final Object lock = new Object();
18
19 public void put(Object obj) {
20 synchronized (lock) {
21 while (this.maxSize == count.get()) {
22 try {
23 lock.wait();
24 } catch (InterruptedException e) {
25 // TODO Auto-generated catch block
26 e.printStackTrace();
27 }
28 }
29 list.add(obj);
30 count.incrementAndGet();
31 System.out.println("新加入的元素是:" + obj);
32 lock.notify();
33 }
34 }
35
36 public Object take() {
37 Object obj = null;
38 synchronized (lock) {
39 while (this.minSize == count.get()) {
40 try {
41 lock.wait();
42 } catch (InterruptedException e) {
43 // TODO Auto-generated catch block
44 e.printStackTrace();
45 }
46 }
47 obj = list.removeFirst();
48 count.decrementAndGet();
49 lock.notify();
50 }
51 return obj;
52 }
53
54 public static void main(String[] args) {
55 final QueueTest01 myQueue = new QueueTest01(5);
56 myQueue.put("a");
57 myQueue.put("b");
58 myQueue.put("c");
59 myQueue.put("d");
60 myQueue.put("e");
61 System.out.println("當前對列的長度:" + myQueue.list.size());
62
63 Thread t1 = new Thread(new Runnable() {
64
65 @Override
66 public void run() {
67 myQueue.put("f");
68 myQueue.put("g");
69 }
70 }, "t1");
71 t1.start();
72 Thread t2 = new Thread(new Runnable() {
73
74 @Override
75 public void run() {
76 Object o1 = myQueue.take();
77 System.out.println("移除的元素爲:" + o1);
78 Object o2 = myQueue.take();
79 System.out.println("移除的元素爲:" + o2);
80 }
81 }, "t2");
82 try {
83 TimeUnit.SECONDS.sleep(2);
84 } catch (InterruptedException e) {
85 // TODO Auto-generated catch block
86 e.printStackTrace();
87 }
88 t2.start();
89
90 }
91 }