forked from CentMeng/JavaFrameTest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyQueue.java
More file actions
107 lines (88 loc) · 2.19 KB
/
Copy pathMyQueue.java
File metadata and controls
107 lines (88 loc) · 2.19 KB
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
package com.msj.sync;
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author Vincent.M mengshaojie@188.com
* @date 2017/3/13 下午4:05
* @copyright ©2017 孟少杰 All Rights Reserved
* @desc 模拟queue
*/
public class MyQueue {
private final LinkedList<Object> list = new LinkedList<Object>();
private final AtomicInteger count = new AtomicInteger(0);
private final int maxSize;
private final int minSize = 0;
private final Object lock = new Object();
public MyQueue (int maxSize){
this.maxSize = maxSize;
}
public void put (Object obj) {
synchronized(lock){
while(count.get() == maxSize){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.add(obj);
count.getAndIncrement();
System.out.println(" 元素 " + obj + " 被添加 ");
lock.notify();
}
}
public Object take(){
Object temp = null;
synchronized (lock) {
while(count.get() == minSize){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count.getAndDecrement();
temp = list.removeFirst();
System.out.println(" 元素 " + temp + " 被消费 ");
lock.notify();
}
return temp;
}
public int size(){
return count.get();
}
public static void main(String[] args) throws Exception {
final MyQueue m = new MyQueue(5);
m.put("a");
m.put("b");
m.put("c");
m.put("d");
m.put("e");
System.out.println("当前元素个数:" + m.size());
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
m.put("h");
m.put("i");
}
}, "t1");
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
Object t1 = m.take();
//System.out.println("被取走的元素为:" + t1);
Thread.sleep(1000);
Object t2 = m.take();
//System.out.println("被取走的元素为:" + t2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "t2");
t1.start();
Thread.sleep(1000);
t2.start();
}
}