public class MyBlockQueue<T> {
private static Object[] queue;
private static int putIndex;
private static int takeIndex;
private static int size;
public MyBlockQueue(int len){
queue=new Object[len];
}
private void put(T e){
if(queue.length==size){
new RuntimeException("队列已满");
}
queue[putIndex]=e;
putIndex=(putIndex+1)%queue.length;
size++;
}
private T take(){
if (size==0){
new RuntimeException("队列空了");
}
T t=(T)queue[takeIndex];
queue[takeIndex]=null;
takeIndex=(takeIndex+1)%queue.length;
size--;
return t;
}
private int size(){
return size;
}
public static void main(String[] args) {
MyBlockQueue<Integer> myBlockQueue=new MyBlockQueue(4);
myBlockQueue.put(1);
myBlockQueue.put(2);
myBlockQueue.put(3);
myBlockQueue.put(4);
for (Object x:queue){
System.out.println((Integer)x);
}
System.out.println("------------------------------------------");
myBlockQueue.take();
for (Object x:queue){
System.out.println((Integer)x);
}
System.out.println("------------------------------------------");
myBlockQueue.put(5);
for (Object x:queue){
System.out.println((Integer)x);
}
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1f8bfce624e3cb76faa6574fc1fb0dee.png#pic_center)
public class MyBlockQueue<T> {
private Object[] queue;
private int putIndex;
private int takeIndex;
private int size;
public MyBlockQueue(int len){
queue=new Object[len];
}
private synchronized void put(T e) throws InterruptedException {
while (queue.length==size){
this.wait();
}
queue[putIndex]=e;
putIndex=(putIndex+1)%queue.length;
size++;
this.notifyAll();
}
private synchronized T take() throws InterruptedException {
while (size==0){
wait();
}
T t=(T)queue[takeIndex];
queue[takeIndex]=null;
takeIndex=(takeIndex+1)%queue.length;
size--;
notifyAll();
return t;
}
private synchronized int size(){
return size;
}
public static void main(String[] args) {
MyBlockQueue<Integer> myBlockQueue=new MyBlockQueue(4);
for (int i=0;i<3;i++){
new Thread(new Runnable() {
@Override
public void run() {
try {
for (int j=0;j<10;j++){
myBlockQueue.put(j);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
for (int i=0;i<3;i++){
new Thread(new Runnable() {
@Override
public void run() {
try {
for (; ; ){
int j = myBlockQueue.take();
System.out.println(Thread.currentThread().getName() + ":" + j);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
}