- 阻塞队列
public class MyArrayBlockingQueue {
private long[] array;
private int frontIndex;
private int rearIndex;
private int size;
public MyArrayBlockingQueue(int capacity){
array =new long[capacity];
frontIndex=0;
rearIndex=0;
size=0;
}
public synchronized void put(long e) throws InterruptedException {
while (array.length==size){
this.wait();
}
array[rearIndex]=e;
rearIndex++;
if (rearIndex ==array.length){
rearIndex=0;
}
size++;
notifyAll();
}
public synchronized long take() throws InterruptedException {
while (size==0){
wait();
}
long e=array[frontIndex];
frontIndex++;
if (frontIndex==array.length){
frontIndex=0;
}
size--;
notifyAll();
return e;
}
}
- 测试
package JavaSE.线程.blockQueue;
import java.util.Scanner;
public class Test {
static MyArrayBlockingQueue queue =new MyArrayBlockingQueue(3);
static class MyThread extends Thread {
@Override
public void run() {
Scanner sc =new Scanner(System.in);
long e=sc.nextLong();
try {
queue.put(e);
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
MyThread thread =new MyThread();
thread.start();
long e=queue.take();
System.out.println(e);
}
}