Java 线程池 SingleThreadExecutor是Executors封装好的4种常见的功能线程池之一,它是只有核心线程的单线程的线程池,可以确保所有任务按照指定的顺序在一个线程中执行。本文主要介绍 SingleThreadExecutor的使用及示例代码。

1、SingleThreadExecutor简介

SingleThreadExecutor是只有 1 个核心线程,无非核心线程,执行完立即回收,任务队列为链表结构的有界队列。一般是用在所有任务按照指定的顺序在一个线程中执行的使用场景,但不适合并发可能引起 IO 阻塞性及影响 UI 线程响应的操作,如数据库操作、文件操作等。相对于通过使用 ThreadPoolExecutor 的方式,使用SingleThreadExecutor更方便,有些参数可能不需要设置,可以根据实现情况使用。

2、newSingleThreadExecuto源码

public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>()));
}
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>(),
                                threadFactory));
}

3、使用示例

import java.util.concurrent.*;
import java.util.Date; 
import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class Main {
  public static void main(String[] args) throws Exception {
    
    
    
    ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
    // 需执行的任务
    Runnable task =new Runnable(){
      public void run() {
              Date date=new Date();
              DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
              System.out.println(" 当前时间为:"+dateFormat.format(date));
      }
    };
    //添加任务
    singleThreadExecutor.execute(task);

    singleThreadExecutor.awaitTermination(10000, TimeUnit.MILLISECONDS);
    System.exit(0); //success
  }
}

推荐文档