BlockingQueue和DelayQueue学习

来源:互联网 发布:nba2k13捏脸详细数据 编辑:程序博客网 时间:2024/05/20 10:22
一、BlockingQueue(查看Java6API
在包java.util.concurrent 下
public interface BlockingQueue<E> extends Queue<E>
支持两个附加操作的 Queue,这两个操作是:获取元素时等待队列变为非空,以及存储元素时等待空间变得可用。
BlockingQueue 方法以四种形式出现,对于不能立即满足但可能在将来某一时刻可以满足的操作,这四种形式的处理方式不同:第一种是抛出一个异常,第二种是返回一个特殊值(null 或 false,具体取决于操作),第三种是在操作可以成功前,无限期地阻塞当前线程,第四种是在放弃前只在给定的最大时间限制内阻塞。下表中总结了这些方法:

抛出异常特殊值阻塞超时插入add(e)offer(e)put(e)offer(e, time, unit)移除remove()poll()take()poll(time, unit)检查element()peek()不可用不可用
  • BlockingQueue 不接受 null 元素。试图 add、put 或 offer 一个 null 元素时,某些实现会抛出 NullPointerException。null 被用作指示 poll 操作失败的警戒值。 
  • BlockingQueue 可以是限定容量的。它在任意给定时间都可以有一个 remainingCapacity,超出此容量,便无法无阻塞地 put 附加元素。没有任何内部容量约束的 BlockingQueue 总是报告 Integer.MAX_VALUE 的剩余容量。 
  • BlockingQueue 实现主要用于生产者-使用者队列,但它另外还支持 Collection 接口。因此,举例来说,使用 remove(x) 从队列中移除任意一个元素是有可能的。然而,这种操作通常不 会有效执行,只能有计划地偶尔使用,比如在取消排队信息时。 
  • BlockingQueue 实现是线程安全的。所有排队方法都可以使用内部锁或其他形式的并发控制来自动达到它们的目的。然而,大量的 Collection 操作(addAll、containsAll、retainAll 和 removeAll)没有 必要自动执行,除非在实现中特别说明。因此,举例来说,在只添加了 c 中的一些元素后,addAll(c) 有可能失败(抛出一个异常)。 
  • BlockingQueue 实质上不 支持使用任何一种“close”或“shutdown”操作来指示不再添加任何项。这种功能的需求和使用有依赖于实现的倾向。例如,一种常用的策略是:对于生产者,插入特殊的 end-of-stream 或 poison 对象,并根据使用者获取这些对象的时间来对它们进行解释。

以下是基于典型的生产者-使用者场景的一个用例。注意,BlockingQueue 可以安全地与多个生产者和多个使用者一起使用。
class Producer implements Runnable {   private final BlockingQueue queue;   Producer(BlockingQueue q) { queue = q; }   public void run() {     try {       while(true) { queue.put(produce()); }     } catch (InterruptedException ex) { ... handle ...}   }   Object produce() { ... } } class Consumer implements Runnable {   private final BlockingQueue queue;   Consumer(BlockingQueue q) { queue = q; }   public void run() {     try {       while(true) { consume(queue.take()); }     } catch (InterruptedException ex) { ... handle ...}   }   void consume(Object x) { ... } } class Setup {   void main() {     BlockingQueue q = new SomeQueueImplementation();     Producer p = new Producer(q);     Consumer c1 = new Consumer(q);     Consumer c2 = new Consumer(q);     new Thread(p).start();     new Thread(c1).start();     new Thread(c2).start();   } }
1)BlockingQueue定义的常用方法如下: 
    1。add(anObject):把anObject加到BlockingQueue里,即如果BlockingQueue可以容纳,则返回true,否则报异常
    2。offer(anObject):表示如果可能的话,将anObject加到BlockingQueue里,即如果BlockingQueue可以容纳,则返回true,否则返回false.
    3。put(anObject):把anObject加到BlockingQueue里,如果BlockQueue没有空间,则调用此方法的线程被阻断直到BlockingQueue里面有空间再继续.
    4。poll(time):取走BlockingQueue里排在首位的对象,若不能立即取出,则可以等time参数规定的时间,取不到时返回null
    5。take():取走BlockingQueue里排在首位的对象,若BlockingQueue为空,阻断进入等待状态直到Blocking有新的对象被加入为止 
2)BlockingQueue有四个具体的实现类,根据不同需求,选择不同的实现类 
    1。ArrayBlockingQueue:规定大小的BlockingQueue,其构造函数必须带一个int参数来指明其大小.其所含的对象是以FIFO(先入先出)顺序排序的.
    2。LinkedBlockingQueue:大小不定的BlockingQueue,若其构造函数带一个规定大小的参数,生成的BlockingQueue有大小限制,若不带大小参数,所生成的BlockingQueue的大小由Integer.MAX_VALUE来决定.其所含的对象是以FIFO(先入先出)顺序排序的
    3。PriorityBlockingQueue:类似于LinkedBlockQueue,但其所含对象的排序不是FIFO,而是依据对象的自然排序顺序或者是构造函数的Comparator决定的顺序.
    4。SynchronousQueue:特殊的BlockingQueue,对其的操作必须是放和取交替完成的. 
3)LinkedBlockingQueue和ArrayBlockingQueue比较起来,它们背后所用的数据结构不一样,导致LinkedBlockingQueue的数据吞吐量要大于ArrayBlockingQueue,但在线程数量很大时其性能的可预见性低于ArrayBlockingQueue.
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class BlockingQueueTest {
    public static void main(String[] args) {
        final BlockingQueue queue = new ArrayBlockingQueue(3);
        for(int i=0;i<2;i++){
            new Thread(){
                public void run(){
                    while(true){
                        try {
                            Thread.sleep((long)(Math.random()*1000));
                            System.out.println(Thread.currentThread().getName() + "准备放数据!");      
                            queue.put(1);
                            System.out.println(Thread.currentThread().getName() + "已经放了数据," +
                                        "队列目前有" + queue.size() + "个数据");
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
               
            }.start();
        }
       
        new Thread(){
            public void run(){
                while(true){
                    try {
                        //将此处的睡眠时间分别改为100和1000,观察运行结果
                        Thread.sleep(1000);
                        System.out.println(Thread.currentThread().getName() + "准备取数据!");
                        queue.take();
                        System.out.println(Thread.currentThread().getName() + "已经取走数据," +    
                                "队列目前有" + queue.size() + "个数据");                    
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
           
        }.start();            
    }
}

二、DelayQueue

java.util.concurrent  
public class DelayQueue<E extends Delayed> extends AbstractQueue<E> implements BlockingQueue<E>
而接口public interface Delayed extends Comparable<Delayed>,一种混合风格的接口,用来标记那些应该在给定延迟时间之后执行的对象。此接口的实现必须定义一个 compareTo 方法,该方法提供与此接口的 getDelay 方法一致的排序。
Delayed 元素的一个无界阻塞队列,只有在延迟期满时才能从中提取元素。该队列的头部 是延迟期满后保存时间最长的 Delayed 元素。如果延迟都还没有期满,则队列没有头部,并且 poll 将返回 null。当一个元素的 getDelay(TimeUnit.NANOSECONDS) 方法返回一个小于等于 0 的值时,将发生到期。即使无法使用 take 或 poll 移除未到期的元素,也不会将这些元素作为正常元素对待。例如,size 方法同时返回到期和未到期元素的计数。此队列不允许使用 null 元素。

应用场景:
a) 关闭空闲连接。服务器中,有很多客户端的连接,空闲一段时间之后需要关闭之。
b) 缓存。缓存中的对象,超过了空闲时间,需要从缓存中移出。
c) 任务超时处理。在网络协议滑动窗口请求应答式交互时,处理超时未响应的请求。

一种笨笨的办法就是,使用一个后台线程,遍历所有对象,挨个检查。这种笨笨的办法简单好用,但是对象数量过多时,可能存在性能问题,检查间隔时间不好设置,间隔时间过大,影响精确度,多小则存在效率问题。而且做不到按超时的时间顺序处理。 

业务场景一:多考生考试

该场景来自于http://ideasforjava.iteye.com/blog/657384,模拟一个考试的日子,考试时间为120分钟,30分钟后才可交卷,当时间到了,或学生都交完卷了考试结束。

这个场景中几个点需要注意:

  1. 考试时间为120分钟,30分钟后才可交卷,初始化考生完成试卷时间最小应为30分钟
  2. 对于能够在120分钟内交卷的考生,如何实现这些考生交卷
  3. 对于120分钟内没有完成考试的考生,在120分钟考试时间到后需要让他们强制交卷
  4. 在所有的考生都交完卷后,需要将控制线程关闭

实现思想:用DelayQueue存储考生(Student类),每一个考生都有自己的名字和完成试卷的时间,Teacher线程对DelayQueue进行监控,收取完成试卷小于120分钟的学生的试卷。当考试时间120分钟到时,先关闭Teacher线程,然后强制DelayQueue中还存在的考生交卷。每一个考生交卷都会进行一次countDownLatch.countDown(),当countDownLatch.await()不再阻塞说明所有考生都交完卷了,而后结束考试。

package com.my.base.concurrent.delayQueue;import java.util.Iterator;import java.util.Random;import java.util.concurrent.CountDownLatch;import java.util.concurrent.DelayQueue;import java.util.concurrent.Delayed;import java.util.concurrent.TimeUnit;/** *this project is created for my partactice. *In the  project I will write the mybatis by myself * *2014-1-10  下午9:43:48 *@author 孙振超   mychaoyue2011@163.com */public class Exam {    /**     *     *2014-1-10 下午9:43:48 by 孙振超     *     *@param args     *void     * @throws InterruptedException      */    public static void main(String[] args) throws InterruptedException {        // TODO Auto-generated method stub        int studentNumber = 20;        CountDownLatch countDownLatch = new CountDownLatch(studentNumber+1);        DelayQueue< Student> students = new DelayQueue<Student>();        Random random = new Random();        for (int i = 0; i < studentNumber; i++) {            students.put(new Student("student"+(i+1), 30+random.nextInt(120),countDownLatch));        }        Thread teacherThread =new Thread(new Teacher(students));         students.put(new EndExam(students, 120,countDownLatch,teacherThread));        teacherThread.start();        countDownLatch.await();        System.out.println(" 考试时间到,全部交卷!");      }}class Student implements Runnable,Delayed{    private String name;    private long workTime;    private long submitTime;    private boolean isForce = false;    private CountDownLatch countDownLatch;        public Student(){}        public Student(String name,long workTime,CountDownLatch countDownLatch){        this.name = name;        this.workTime = workTime;        this.submitTime = TimeUnit.NANOSECONDS.convert(workTime, TimeUnit.NANOSECONDS)+System.nanoTime();        this.countDownLatch = countDownLatch;    }        @Override    public int compareTo(Delayed o) {        // TODO Auto-generated method stub        if(o == null || ! (o instanceof Student)) return 1;        if(o == this) return 0;         Student s = (Student)o;        if (this.workTime > s.workTime) {            return 1;        }else if (this.workTime == s.workTime) {            return 0;        }else {            return -1;        }    }    @Override    public long getDelay(TimeUnit unit) {        // TODO Auto-generated method stub        return unit.convert(submitTime - System.nanoTime(),  TimeUnit.NANOSECONDS);    }    @Override    public void run() {        // TODO Auto-generated method stub        if (isForce) {            System.out.println(name + " 交卷, 希望用时" + workTime + "分钟"+" ,实际用时 120分钟" );        }else {            System.out.println(name + " 交卷, 希望用时" + workTime + "分钟"+" ,实际用时 "+workTime +" 分钟");          }        countDownLatch.countDown();    }    public boolean isForce() {        return isForce;    }    public void setForce(boolean isForce) {        this.isForce = isForce;    }    }class EndExam extends Student{    private DelayQueue<Student> students;    private CountDownLatch countDownLatch;    private Thread teacherThread;        public EndExam(DelayQueue<Student> students, long workTime, CountDownLatch countDownLatch,Thread teacherThread) {        super("强制收卷", workTime,countDownLatch);        this.students = students;        this.countDownLatch = countDownLatch;        this.teacherThread = teacherThread;    }                @Override    public void run() {        // TODO Auto-generated method stub                teacherThread.interrupt();        Student tmpStudent;        for (Iterator<Student> iterator2 = students.iterator(); iterator2.hasNext();) {            tmpStudent = iterator2.next();            tmpStudent.setForce(true);            tmpStudent.run();        }        countDownLatch.countDown();    }    }class Teacher implements Runnable{    private DelayQueue<Student> students;    public Teacher(DelayQueue<Student> students){        this.students = students;    }        @Override    public void run() {        // TODO Auto-generated method stub        try {            System.out.println(" test start");            while(!Thread.interrupted()){                students.take().run();            }        } catch (Exception e) {            // TODO: handle exception            e.printStackTrace();        }    }    }

 

业务场景二:具有过期时间的缓存

该场景来自于http://www.cnblogs.com/jobs/archive/2007/04/27/730255.html,向缓存添加内容时,给每一个key设定过期时间,系统自动将超过过期时间的key清除。

这个场景中几个点需要注意:

  1. 当向缓存中添加key-value对时,如果这个key在缓存中存在并且还没有过期,需要用这个key对应的新过期时间
  2. 为了能够让DelayQueue将其已保存的key删除,需要重写实现Delayed接口添加到DelayQueue的DelayedItem的hashCode函数和equals函数
  3. 当缓存关闭,监控程序也应关闭,因而监控线程应当用守护线程

具体实现如下:

package com.my.base.concurrent.delayQueue;import java.util.Random;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.DelayQueue;import java.util.concurrent.Delayed;import java.util.concurrent.TimeUnit;/** *Cache.java * * Created on 2014-1-11 上午11:30:36 by sunzhenchao mychaoyue2011@163.com */public class Cache<K, V> {    public ConcurrentHashMap<K, V> map = new ConcurrentHashMap<K, V>();    public DelayQueue<DelayedItem<K>> queue = new DelayQueue<DelayedItem<K>>();            public void put(K k,V v,long liveTime){        V v2 = map.put(k, v);        DelayedItem<K> tmpItem = new DelayedItem<K>(k, liveTime);        if (v2 != null) {            queue.remove(tmpItem);        }        queue.put(tmpItem);    }        public Cache(){        Thread t = new Thread(){            @Override            public void run(){                dameonCheckOverdueKey();            }        };        t.setDaemon(true);        t.start();    }        public void dameonCheckOverdueKey(){        while (true) {            DelayedItem<K> delayedItem = queue.poll();            if (delayedItem != null) {                map.remove(delayedItem.getT());                System.out.println(System.nanoTime()+" remove "+delayedItem.getT() +" from cache");            }            try {                Thread.sleep(300);            } catch (Exception e) {                // TODO: handle exception            }        }    }        /**     * TODO     * @param args     * 2014-1-11 上午11:30:36     * @author:孙振超     * @throws InterruptedException      */    public static void main(String[] args) throws InterruptedException {        Random random = new Random();        int cacheNumber = 10;        int liveTime = 0;        Cache<String, Integer> cache = new Cache<String, Integer>();                for (int i = 0; i < cacheNumber; i++) {            liveTime = random.nextInt(3000);            System.out.println(i+"  "+liveTime);            cache.put(i+"", i, random.nextInt(liveTime));            if (random.nextInt(cacheNumber) > 7) {                liveTime = random.nextInt(3000);                System.out.println(i+"  "+liveTime);                cache.put(i+"", i, random.nextInt(liveTime));            }        }        Thread.sleep(3000);        System.out.println();    }}class DelayedItem<T> implements Delayed{    private T t;    private long liveTime ;    private long removeTime;        public DelayedItem(T t,long liveTime){        this.setT(t);        this.liveTime = liveTime;        this.removeTime = TimeUnit.NANOSECONDS.convert(liveTime, TimeUnit.NANOSECONDS) + System.nanoTime();    }        @Override    public int compareTo(Delayed o) {        if (o == null) return 1;        if (o == this) return  0;        if (o instanceof DelayedItem){            DelayedItem<T> tmpDelayedItem = (DelayedItem<T>)o;            if (liveTime > tmpDelayedItem.liveTime ) {                return 1;            }else if (liveTime == tmpDelayedItem.liveTime) {                return 0;            }else {                return -1;            }        }        long diff = getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);        return diff > 0 ? 1:diff == 0? 0:-1;    }    @Override    public long getDelay(TimeUnit unit) {        return unit.convert(removeTime - System.nanoTime(), unit);    }    public T getT() {        return t;    }    public void setT(T t) {        this.t = t;    }    @Override    public int hashCode(){        return t.hashCode();    }        @Override    public boolean equals(Object object){        if (object instanceof DelayedItem) {            return object.hashCode() == hashCode() ?true:false;        }        return false;    }    }



参考:
http://www.cnblogs.com/jobs/archive/2007/04/27/730255.html
http://www.cnblogs.com/sunzhenchao/p/3515085.html

0 0
原创粉丝点击