Android thread
threads
进程模型基于两个概念:资源分组处理与执行。
进程用于把资源集中到一起,而线程是在CPU上被调度执行的实体。
在同一个进程里并行多个线程(共享地址空间,全局变量等)是对在同一个pc上并行运行多个进程(共享物理内存,磁盘,打印机)的模拟。
每个进程的内容,多个线程可以共享:地址空间,全局变量,打开的文件,子进程,信号与信号处理程序,账户信息
每个线程中的内容:程序计数器( 用于存放下一条指令所在单元的地址的地方),寄存器,堆栈,状态
资源管理的单位是进程,cpu调度的单位是线程,
线程的目标是:多个线程共享一组资源,并行执行,为了同一个任务而共同工作。
线程的状态:运行,阻塞,就绪,终止。
由于每个线程调度执行的历史是不一样的,所有每个线程需要有自己的堆栈。
java thread
利用对象可以把一个程序分割成相互独立的区域。
将一个程序转换成多个独立运行的子任务,这个子任务就是线程。
考虑创建线程时机:程序的一些部分同特定的事件或者资源联系在一起,同时又不想为它而暂停程序的其他部分的执行。
主要用途可以构建反应灵敏的用户界面
对象和类都有自己的锁,对于访问某个关键共享资源的所有方法,设为synchronized即可。或者使用同步块syncObject对一段代码加锁。
新(New):可被调度,已创建但没有启动
可运行(Runnable):有CPU即就可以运行,线程可能运行也可能不在运行。
阻塞(Blocked):被阻塞,线程可以运行。如果线程进入可运行态才可以再次运行。
死(Dead):从run返回后线程就死了。
android thread
AsyncTask封装了线程池和Handler
HandlerThread具有消息循环的线程
IntentService执行后台服务
Async Task
不适合特别耗时操作(大约几秒钟),特别耗时需要用线程池,如Excutor,ThreadPoolExcetor,FutureTask;
asyncTask可以在UI线程里方便的使用,执行后台操作,并且将结果返回到UI线程,不需要自己操作线程或者Handler。
AsyncTask只在一个单独的后台线程执行,
一些概念:
-
Callable
A task that returns a result and may throw an exception. Implementors define a single method with no arguments called call.
Runnable
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run.
This interface is designed to provide a common protocol for objects that wish to execute code while they are active. For example, Runnable is implemented by class Thread. Being active simply means that a thread has been started and has not yet been stopped.Future
A Future represents the result of an asynchronous computation.FutureTask
A cancellable asynchronous computation. This class provides a base implementation of Future, with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation. The result can only be retrieved when the computation has completed; the get methods will block if the computation has not yet completed. Once the computation has completed, the computation cannot be restarted or cancelled (unless the computation is invoked using runAndReset()).Executor
An object that executes submitted Runnable tasks. This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc.
For example, rather than invoking new Thread(new(RunnableTask())).start() for each of a set of tasks, you might use:
Executor executor = anExecutor;
executor.execute(new RunnableTask1());
executor.execute(new RunnableTask2());
...ArrayDeque
Resizable-array implementation of the Deque interface. Array deques have no capacity restrictions; they grow as necessary to support usage. They are not thread-safe; in the absence of external synchronization, they do not support concurrent access by multiple threads. Null elements are prohibited. This class is likely to be faster than Stack when used as a stack, and faster than LinkedList when used as a queue.ThreadPoolExecutor
An ExecutorService that executes each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods.
Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.BlockingDeque
A Deque that additionally supports blocking operations that wait for the deque to become non-empty when retrieving an element, and wait for space to become available in the deque when storing an element.
HandlerThread
结合了Handler的Thread。
IntentService
可以执行耗时后台任务。
IntentService is a base class for Services that handle asynchronous requests (expressed as android.content.Intents) on demand. Clients send requests through
android.content.Context.startService(android.content.Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
This "work queue processor" pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(android.content.Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.
All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.
ThreadPool
优点:
- 可以重用线程,避免开销
- 控制最大并发数
- 可以管理线程
ThreadPoolExecutor
- corePoolSize:核心线程数
- maximumPoolSize:最大线程数
- keepAliveTime:非核心线程超时时间
- workQueue:线程池任务队列
- threadFactory:创建新线程的线程工厂
FixedThreadPool,CachedThreadPool,ScheduledThreadPool,SingleThreadPool