Android thread

2017-01-18  本文已影响0人  null0007

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只在一个单独的后台线程执行,

一些概念:

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

优点:

  1. 可以重用线程,避免开销
  2. 控制最大并发数
  3. 可以管理线程

ThreadPoolExecutor

FixedThreadPool,CachedThreadPool,ScheduledThreadPool,SingleThreadPool

上一篇 下一篇

猜你喜欢

热点阅读