利用前面学到的知识 写一个我们自己的mq队列
不多说直接亮代码
package com.ghost.concurrent;
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 消息队列
* @author Ghost
*/
public abstract class Mq {
/**
* 队列容器
*/
private final LinkedList<Object> list = new LinkedList<Object>();
/**
* 当前队列长度
*/
private final AtomicInteger count = new AtomicInteger(0);
/**
* 队列最小值
*/
private final int min=0;
/**
* 队列最大值
*/
private final int max;
/**
* 锁对象
*/
private final Object lock = new Object();
public Mq(int max){
this.max=max;
}
/**
*
* @Description: TODO(插入方法)
* @param @param obj
* @return void
* @author LJ
*/
public void put(Object obj){
synchronized (lock) {
try {
if(count.get()==max){
lock.wait();
}
list.add(obj);
count.getAndIncrement();
lock.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
*
* @Description: TODO(获取)
* @param @return
* @return Object
* @author LJ
*/
public Object take(){
Object obj = null;
synchronized (lock) {
try {
while(true){
if(count.get()==min){
lock.wait();
}
obj = list.removeFirst();
count.getAndDecrement();
try {
spvoice(obj);
} catch (Exception e) {
e.printStackTrace();
}
lock.notify();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return obj;
}
}
/**
*
* @Description: TODO(子类继承实现)
* @param @param obj
* @return void
* @author LJ
*/
public abstract void spvoice(Object obj);
}
package com.ghost.concurrent;
public class MyMq extends Mq{
public MyMq(int max) {
super(max);
}
@Override
public void spvoice(Object obj) {
System.out.println("获取到一个对象:"+obj);
//模拟执行时间
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.ghost.concurrent;
public class Test1 {
public static void main(String[] args) {
final MyMq myMQ = new MyMq(100);
T t1 = new T(myMQ,"1");
T t2 = new T(myMQ,"2");
T t3 = new T(myMQ,"3");
T t4 = new T(myMQ,"4");
T t5 = new T(myMQ,"5");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
new Thread(new Runnable() {
@Override
public void run() {
myMQ.take();
}
}).start();;
}
}
class T extends Thread{
MyMq m;
String name;
public T(MyMq m,String name){
this.m=m;
this.name=name;
}
@Override
public void run() {
for(int i=0;i<10;i++){
m.put(name+":"+i);
}
}
}
这是一个阻塞式的队列 大家看看就好!