package com;
import java.util.Arrays;
import java.util.concurrent.ArrayBlockingQueue;
public class BlockQueueTests {
public static void main(String[] args) {
BlockQueueContainer<Integer> ic = new BlockQueueContainer<>(3);
new Thread(new Runnable() {
@Override
public void run() {
int i =1;
while (true) {
ic.put(i++);
System.out.println(Arrays.toString(ic.getArray()));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true){
Object take = ic.take();
System.out.println(take);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}).start();
}
}
class BlockQueueContainer<T>{
/**
* 存储数据的容器
*/
private Object[] array;
/**
* 记录有效元素个数
*/
private int size;
public BlockQueueContainer(int cap){
array = new Object[cap];
}
/**
* 用于向容器放数据
* 1.阻塞方法wait()
* 2.唤醒方法notify()
*/
public synchronized void put(T t){
//1.放数据之前判定容器是否已满,满了则阻塞当前线程
while (size == array.length) {
try {
this.wait();
} catch (InterruptedException e) {}
}
//2.在size位置放数据
array[size] = t;
//3.有效元素个数加1(也是确定下一个元素的位置)
size++;
//通知取数据的线程可以取数据了
this.notifyAll();
}
/**
* 用于向容器取数据
* @return
*/
public synchronized T take(){
while (size == 0){
try {
this.wait();
}catch (Exception e){}
}
T data = (T)array[0];
System.arraycopy(array,1,array,0, --size);
this.notifyAll();
return data;
}
public Object[] getArray() {
return array;
}
public void setArray(Object[] array) {
this.array = array;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
【无标题】
最新推荐文章于 2024-10-17 19:11:48 发布