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
主线程退出了
网友评论