Running code task instances in the Android thread pool

This section shows how to perform tasks in the thread pool. The process is to add a task to the work queue of the thread pool. When a thread is available (after executing other tasks, idle, or not yet executing tasks), the ThreadPoolExecutor will take the task from the queue and run it in the thread. This lesson also shows you how to stop a running task.

Execute tasks on threads in the thread pool

Pass in the runnable object in ThreadPoolExecutor. Execute() to start the task. This method adds the task to the thread pool work queue. When there is an idle thread, the manager will take out the longest waiting task and run it on the thread.

When ThreadPoolExecutor starts runnable, the run () method is called automatically.

Interrupt running code

To stop a task, you need to interrupt the process of the task. You need to save a handle of the current thread when creating a task. For example:

To interrupt a thread, just call thread. Interrupt(). Tip: Thread objects are system controlled and can be edited outside your app process. For this reason, you need to add an access lock before interrupting it and put it into a synchronization block:

In most cases, thread. Interrupt () stops the thread immediately. However, it will only stop waiting threads, but will not interrupt CPU or network intensive tasks. To prevent the system from slowing down, you should test requests waiting for interrupts before attempting operations.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>