handler.postDelayed 对比 ScheduledThreadPoolExecutor.scheduleWithFixedDelay

handler.postDelayed vs ScheduledThreadPoolExecutor.scheduleWithFixedDelay

new ScheduledThreadPoolExecutor(1).scheduleWithFixedDelayHandler.postDelayed()我该如何选择?

它们一样吗?它们之间有什么区别?

Future scheduledFuture = scheduledExecutor.scheduleWithFixedDelay(runnable, 0, delay, TimeUnit.MILLISECONDS);

new Handler().postDelayed(runnable, delay);

A ScheduledExecutorService 是一个非常通用的线程管理解决方案。你用一定数量的工作线程初始化它,然后给它工作单元。您可以 delay/time 并重复工作单元。

一个Handler是一个Class,用于线程之间的通信。您已将 Looper 传递给它的线程上的处理程序 运行s。如果你的处理程序在 MainThread 中实例化,那么它 运行 在 MainThread 上,如果你创建一个带有 Looper (HandlerThread) 的工作线程并将它的 Looper 传递给 Handler ,那么它 运行 在那个工作线程上.

Basically both of them Execute the task after a delay, but Do note that scheduledExecutor.scheduleWithFixedDelay will always execute in the worker thread , were as Handler.postDelayed will run on Thread where it has been attached to (Either MainThread or BackGround Thread)

Handler - 在可选延迟后在 UIThread 上执行可运行任务

ScheduledThreadPoolExecutor - 使用后台线程池执行周期性任务

scheduleWithFixedDelay

scheduleWithFixedDelay Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next. If any execution of the task encounters an exception, subsequent executions are suppressed. Otherwise, the task will only terminate via cancellation or termination of the executor.

ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                        long initialDelay,
                                        long delay,
                                        TimeUnit unit)

使用定时器有一些缺点

  • 它只创建一个线程来执行任务,如果一个任务花费的时间太长运行,其他任务就会受到影响。

  • 它不处理任务抛出的异常,线程只是终止,这会影响其他计划任务,它们永远不会运行

Handler

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

Handler 专为

而设计
  1. 安排消息并运行能够在未来的某个时间点执行;和

  2. 将要在不同于您自己的线程上执行的操作排队。