import java.util.LinkedList;
import java.util.stream.IntStream;
/**
*/
public class BlockArrayTest {
private static int lenth = 10;
private static LinkedList<Integer> list = new LinkedList<>();
private static Object lock = new Object();
public static void main(String[] args) throws Exception{
BlockArray array = new BlockArray();
new Thread(()->{
IntStream.range(0,100).forEach( i -> {
System.out.println("put " + i);
array.put(i);
});
}).start();
Thread.sleep(100L);
new Thread(()->{
IntStream.range(0,100).forEach( i -> {
System.out.println("get " + array.get());
});
}).start();
}
static class BlockArray {
public void put (Integer i) {
synchronized (lock) {
while (list.size() == lenth) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.add(i);
System.out.println(list);
lock.notify();
}
}
public Integer get () {
synchronized (lock) {
while (list.size() == 0) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Integer pop = list.pop();
lock.notify();
return pop;
}
}
}
}
通过wait、notify来实现阻塞队列
最新推荐文章于 2022-07-14 12:06:36 发布