三种方法
题目一
自定义同步容器,容器容量上限为10。可以在多线程中应用,并保证数据线程安全。
方式一:synchronized/wait/notifyAll
public class Test_04<E> {
private LinkedList<E> list = new LinkedList<E>();
private final int MAX_SIZE = 10;
private int count = 0;
public synchronized void put(E e) {
while (list.size() == MAX_SIZE) {
try {
this.wait();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
list.add(e);
count++;
this.notifyAll();
}
public synchronized E get() {
E e = null;
while (list.size() == 0) {
try {
this.wait();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
e = list.removeFirst();
count--;
this.notifyAll();
return e;
}
public static void main(String[] args) {
Test_04<Object> m = new Test_04<Object>();
for (int i = 0; i < 2; i++) {
new Thread(() -> {
//容器上限10,25会超出容量限制,会等待
Object object = null;
for (int j = 0; j < 25; j++) {
object = new Object();
m.put