Android计时器任务线程安全

我有一个启动新线程的类,他们使用处理程序在ui线程中编写一个数组,它们是线程安全的.

如果我从计时器任务启动这些线程,它们仍然是ui thred线程安全怎么办?

谢谢!

最佳答案 如果Handler对象绑定到UI线程,则可以安全地更新Handler中的数组(假设该数组也绑定到UI线程).

检查Handler documentation,尤其是这部分:

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.

There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.

它声明Handler代码在它所属的线程上执行.

点赞