SynchronousQueue队列的使用

来源:互联网 发布:himall2.8官方版源码 编辑:程序博客网 时间:2024/06/09 15:08

一直知道java.util.concurrent.Executors#newCachedThreadPool()方法里面使用了SynchronousQueue队列,但是自己在项目中却找不到使用该队列的场景,今天看到这篇文章,于是意淫出一个使用场景:有一个线程数为1的线程池,每次只能并发执行一个任务,当同时有多个任务被提交到该线程池时,抛弃多余的任务,代码如下:

import java.util.concurrent.*;public class SyncQueueTester {    private static ExecutorService executor = new ThreadPoolExecutor(1, 1,            1000, TimeUnit.SECONDS,            new SynchronousQueue<Runnable>(),            new ThreadPoolExecutor.DiscardPolicy());    private static void kickOffEntry(final int index) {        executor.submit(                new Callable<Void>() {                    public Void call() throws InterruptedException {                        System.out.println("start " + index);                        Thread.sleep(999); // pretend to do work                        System.out.println("stop " + index);                        return null;                    }                }        );    }    public static void main(String[] args) throws InterruptedException {        for (int i = 0; i < 20; i++) {            kickOffEntry(i);            Thread.sleep(200);        }        executor.shutdown();    }}

代码中使用了SynchronousQueue,其中DiscardPolicy表示抛弃后续来不及执行的任务。输出结果如下:

start 0stop 0start 5stop 5start 10stop 10start 15stop 15
原创粉丝点击