-
线程的实现方式
-
线程池的使用
SingleThreadExecutor线程池其实只是固定某些参数值的 ThreadPoolExecutor,实例化的代码如下:
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
可以清楚的看到:corePoolSize为1,maximumPoolSize为1,keepAliveTime为0,阻塞队列使用的是LinkedBlockingQueue
而ThreadFactory为默认的defaultThreadFactory,ThreadFactory定义了两个:defaultThreadFactory和privilegedThreadFactory,但是也可以自己定义,实现ThreadFactory接口即可。而默认的拒绝策略RejectedExecutionHandler则为 AbortPolicy,并起所有的拒绝策略都是实现接口RejectedExecutionHandler
除了默认的之外还包含如下:
SingleThreadExecutor 简单示例如下(其中CountDownLatch 主要是为了等待所有的线程执行完之后再结束):
public class SingleThreadPoolTest { private static final int threads = 100; private CountDownLatch countDownLatch = new CountDownLatch(threads); /** * singleThreadPool execute * * @throws InterruptedException */ @Test public void test1() throws InterruptedException { System.out.println("---- begin ----"); ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); for (int i = 0; i < threads; i++) { singleThreadExecutor.execute(() -> { printThreadInfo(); }); } countDownLatch.await(); System.out.println("---- end ----"); } /** * singleThreadPool submit * * @throws InterruptedException */ @Test public void test2() throws InterruptedException { System.out.println("---- begin ----"); ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); for (int i = 0; i < threads; i++) { singleThreadExecutor.submit(new Thread(() -> { printThreadInfo(); })); } countDownLatch.await(); System.out.println("---- end ----"); } /** * 打印线程信息 */ private void printThreadInfo() { try { System.out.println(Thread.currentThread().getName()); Thread.sleep(50); } catch (Exception e) { System.out.println(e); } finally { countDownLatch.countDown(); } } }