照着ArrayBlockingQueue自己实现了一些阻塞队列,其原理就是生产者消费者关系,先实现了功能,一些细节(为什么不用wite,notify 为什么不用lock.lock())暂时没有去学习。
队列代码:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created on 2017/8/31.
*/
public class MyBlockingQueue {
final Object[] items=new Object[3];
final ReentrantLock lock=new ReentrantLock();
private final Condition notFull;
private static int num=-1;
public MyBlockingQueue() {
this.notFull = lock.newCondition();
}
public void put(Object item) throws InterruptedException {
// 如果满了则开始阻塞
lock.lockInterruptibly();
try {
while(items.length==num+1){
System.out.println("queue is filled and begin to wite");
notFull.await();
}
num++;
items[num]=item;
System.out.println("put .."+item);
System.out.println("put success and try to notify");
notFull.signal();
}finally {
lock.unlock();
}
}
public Object take(int index) throws InterruptedException {
if (items.length<index){
System.out.println("index is overflow...index="+index+",length="+items.length);
return null;
}
// 为空则阻塞
lock.lockInterruptibly();
try {
while(num==-1){
System.out.println("queue is empty and begin to wite");
notFull.await();
}
Object result=items[num];
items[num]=null;
System.out.println("queue`s "+num+"is already remove");
num--;
System.out.println("try to notify");
notFull.signal();
return result;
}finally {
lock.unlock();
}
}
}
测试类代码:
/**
* Created on 2017/8/31.
*/
public class Mytest {
public static void main(String[] args) {
final MyBlockingQueue queue=new MyBlockingQueue();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i <10 ; i++) {
try {
queue.put(i);
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i <10 ; i++) {
try {
queue.take(0);
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
打印结果:
put ..0
put success and try to notify
queue`s 0is already remove
try to notify
put ..1
put success and try to notify
put ..2
put success and try to notify
put ..3
put success and try to notify
queue is filled and begin to wite
queue`s 2is already remove
try to notify
put ..4
put success and try to notify
queue is filled and begin to wite
queue`s 2is already remove
try to notify
put ..5
put success and try to notify
queue is filled and begin to wite
queue`s 2is already remove
try to notify
put ..6
put success and try to notify
queue is filled and begin to wite
queue`s 2is already remove
try to notify
put ..7
put success and try to notify
queue is filled and begin to wite
queue`s 2is already remove
try to notify
put ..8
put success and try to notify
queue is filled and begin to wite
queue`s 2is already remove
try to notify
put ..9
put success and try to notify
queue`s 2is already remove
try to notify
queue`s 1is already remove
try to notify
queue`s 0is already remove
try to notify