Android thread

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

优点:

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

ThreadPoolExecutor

  • corePoolSize:核心线程数
  • maximumPoolSize:最大线程数
  • keepAliveTime:非核心线程超时时间
  • workQueue:线程池任务队列
  • threadFactory:创建新线程的线程工厂

FixedThreadPool,CachedThreadPool,ScheduledThreadPool,SingleThreadPool

  • ExecutorService

    An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,362评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,330评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,247评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,560评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,580评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,569评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,929评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,587评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,840评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,596评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,678评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,366评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,945评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,929评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,165评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,271评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,403评论 2 342

推荐阅读更多精彩内容

  • 时间 平淡无奇 机械麻木地重复 还没过够大一浑浑噩噩混日子的我 就被时间强推着灌上了学姐的名号 学弟学妹的疑问让我...
    what啥阅读 306评论 0 0
  • 腹有诗书气自华是从小爸妈就念叨的一句话。但,我并不是一个爱读书的女孩子,却极其想要成为这样的女孩子~ 现在的生活的...
    寡清欢阅读 508评论 0 3
  • 01 “我的阅读能力不行,就是因为不爱背单词”; “老师,孩子的阅读题目总丢分,是不是单词量太小?” 在我从事英语...
    白笑笛阅读 1,081评论 0 50
  • 今天继续探讨如何帮助用户找到内容——「搜索」过程产品设计。 我们先看一个完整的搜索用户体验流程:有一个用户小明,进...
    陶然听说阅读 341评论 0 5