美文网首页
Executors.newSingleThreadSchedul

Executors.newSingleThreadSchedul

作者: menghuijia | 来源:发表于2018-08-31 15:08 被阅读0次

    1. Executors.newSingleThreadScheduledExecutor()

    public static void main(String[] args) throws Exception {
        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
        // 1秒打印一次 当前线程名
        service.scheduleAtFixedRate(() -> System.out.println(Thread.currentThread().getName()), 1, 1, TimeUnit.SECONDS);
        // 主线程等待10秒
        TimeUnit.SECONDS.sleep(10);
        System.out.println("主线程退出了");
    }
    

    输出结果了如下:

    pool-1-thread-1
    pool-1-thread-1
    pool-1-thread-1
    pool-1-thread-1
    pool-1-thread-1
    pool-1-thread-1
    pool-1-thread-1
    pool-1-thread-1
    pool-1-thread-1
    主程序退出了
    pool-1-thread-1
    pool-1-thread-1
    pool-1-thread-1
    pool-1-thread-1
    pool-1-thread-1
    pool-1-thread-1
    

    2. Executors.newSingleThreadScheduledExecutor(ThreadFactory threadFactory)

    public static void main(String[] args) throws Exception {
            ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(r -> {
                Thread t = new Thread(r, "SubThread");
                // 设置线程为守护线程,主线程退出,子线程也随之退出
                t.setDaemon(true);
                return t;
            });
            // 1秒打印一次 当前线程名
            service.scheduleAtFixedRate(() -> System.out.println(Thread.currentThread().getName()), 1, 1, TimeUnit.SECONDS);
            // 主线程等待10秒
            TimeUnit.SECONDS.sleep(10);
            System.out.println("主线程退出了");
        }
    

    输出结果了如下:

    SubThread
    SubThread
    SubThread
    SubThread
    SubThread
    SubThread
    SubThread
    SubThread
    SubThread
    SubThread
    主线程退出了
    

    相关文章

      网友评论

          本文标题:Executors.newSingleThreadSchedul

          本文链接:https://www.haomeiwen.com/subject/rcbswftx.html