SynchronousQueue队列的使用
一直知道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 0 stop 0 start 5 stop 5 start 10 stop 10 start 15 stop 15