android 如何管理线程,浅谈Android中线程池的管理

说到线程就要说说线程机制 Handler,Looper,MessageQueue 可以说是三座大山了

Handler

Handler 其实就是一个处理者,或者说一个发送者,它会把消息发送给消息队列,也就是Looper,然后在一个无限循环队列中进行取出消息的操作 mMyHandler.sendMessage(mMessage); 这句话就是我耗时操作处理完了,我发送过去了! 然后在接受的地方处理!简单理解是不是很简单。

一般我们在项目中异步操作都是怎么做的呢?

// 这里开启一个子线程进行耗时操作

new Thread() {

@Override

public void run() {

.......

Message mMessage = new Message();

mMessage.what = 1;

//在这里发送给消息队列

mMyHandler.sendMessage(mMessage);

}

}.start();

/**

* 这里就是处理的地方 通过msg.what进行处理分辨

*/

class MyHandler extends Handler{

@Override

public void handleMessage(Message msg) {

super.handleMessage(msg);

switch (msg.what){

//取出对应的消息进行处理

........

}

}

}

那么我们的消息队列是在什么地方启动的呢?跟随源码看一看

# ActivityThread.main

public static void main(String[] args) {

//省略代码。。。。。

//在这里创建了一个消息队列!

Looper.prepareMainLooper();

ActivityThread thread = new ActivityThread();

thread.attach(false);

if (sMainThreadHandler == null) {

sMainThreadHandler = thread.getHandler();

}

//这句我也没有看懂 这不是一直都不会执行的么

if (false) {

Looper.myLooper().setMessageLogging(new

LogPrinter(Log.DEBUG, "ActivityThread"));

}

Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);

//消息队列跑起来了!

Looper.loop();

throw new RuntimeException("Main thread loop unexpectedly exited");

}

public Handler(Callback callback, boolean async) {

mLooper = Looper.myLooper();

//注意看这里抛出的异常 如果这里mLooper==null

if (mLooper == null) {

throw new RuntimeException(

"Can't create handler inside thread that has not called Looper.prepare()");

}

//获取消息队列

mQueue = mLooper.mQueue;

mCallback = callback;

mAsynchronous = async;

}

以上操作Android系统就获取并且启动了一个消息队列,过多的源码这里不想去描述,免的占用很多篇幅

这里说一下面试常见的一个问题,就是在子线程中可不可以创建一个Handler,其实是可以的,但是谁这么用啊- -

new Thread() {

Handler mHandler = null;

@Override

public void run() {

//在这里获取

Looper.prepare();

mHandler = new Handler();

//在这里启动

Looper.loop();

}

}.start();

多线程的创建

一般我们在开发过程中要开启一个线程都是直接

new Thread() {

@Override

public void run() {

doing.....

}

}.start();

new Thread(new Runnable() {

@Override

public void run() {

doing.....

}

}).start();

注意看,一个传递了Runnable对象,另一个没有,但是这两个有什么不同,为什么要衍生出2个呢?

这里不去看源码,简单叙述一下,实际上Thread是 Runnabled的一个包装实现类 ,Runnable只有一个方法,就 是run() ,在这里以前也想过,为什么Runnable只有一个方法呢,后来的某一次交谈中也算是找到一个答案,可能是因为多拓展,可能JAVA语言想拓展一些其他的东西,以后就直接在Runnable再写了。不然我是没有想到另一答案为什么都要传递一个Runnable,可能就像我们开发中的baseActivity一样吧

线程常用的操作方法

wait() 当一个线程执行到了wait() 就会进去一个和对象有关的等待池中,同时失去了释放当前对象的机所,使其他线程可以访问,也就是让其他线程可以调用notify()唤醒

sleep() 调用得线程进入睡眠状态,不能该改变对象的机锁,其他线程不能访问

join() 就等自己完事

yidld 你急你先来

简单的白话叙述其实也就是这样,希望能看看demo然后理解一下。

一些其他的方法,Callable,Future,FutureTask

Runnable是线程管理的拓展接口,不可以运用于线程池,所以你总要有方法可以在线程池中管理啊所以Callable,Future,FutureTask就是可以在线程池中开启线程的接口。

Future定义了规范的接口,如get(),isDone(),isCancelled()... FutureTask 是他的实现类这里简单说一下他的用法

/**

* ================================================

* 作 者:夏沐尧 Github地址:https://github.com/XiaMuYaoDQX

* 版 本:1.0

* 创建日期: 2018/1/10

* 描 述:

* 修订历史:

* ================================================

*/

class FutureDemo {

//创建一个单例线程

static ExecutorService mExecutor = Executors.newSingleThreadScheduledExecutor();

public static void main(String[] args) throws ExecutionException, InterruptedException {

ftureWithRunnable();

ftureWithCallable();

ftureTask();

}

/**

* 没有指定返回值,所以返回的是null,向线程池中提交的是Runnable

*

* @throws ExecutionException

* @throws InterruptedException

*/

private static void ftureWithRunnable() throws ExecutionException, InterruptedException {

Future> result1 = mExecutor.submit(new Runnable() {

@Override

public void run() {

fibc(20);

System.out.println(Thread.currentThread().getName());

}

});

System.out.println("Runnable" + result1.get());

}

/**

* 提交了Callable,有返回值,可以获取阻塞线程获取到数值

*

* @throws ExecutionException

* @throws InterruptedException

*/

private static void ftureWithCallable() throws ExecutionException, InterruptedException {

Future result2 = mExecutor.submit(new Callable() {

@Override

public Integer call() throws Exception {

System.out.println(Thread.currentThread().getName());

return fibc(20);

}

});

System.out.println("Callable" + result2.get());

}

/**

* 提交的futureTask对象

* @throws ExecutionException

* @throws InterruptedException

*/

private static void ftureTask() throws ExecutionException, InterruptedException {

FutureTask futureTask = new FutureTask(new Callable() {

@Override

public Integer call() throws Exception {

System.out.println(Thread.currentThread().getName());

return fibc(20);

}

});

mExecutor.submit(futureTask);

System.out.println("futureTask" + futureTask.get());

}

private static int fibc(int num) {

if (num == 0) {

return 0;

}

if (num == 1) {

return 1;

}

return fibc(num - 1) + fibc(num - 2);

}

}

线程池

Java通过Executors提供线程池,分别为:

newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。

newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。

newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。

newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

示例代码

newCachedThreadPool

创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。示例代码如下:

public class ThreadPoolExecutorTest {

public static void main(String[] args) {

ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

for (int i = 0; i < 10; i++) {

final int index = i;

try {

Thread.sleep(index * 1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

cachedThreadPool.execute(new Runnable() {

public void run() {

System.out.println(index);

}

});

}

}

}

线程池为无限大,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程。

newFixedThreadPool

创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。示例代码如下:

public class ThreadPoolExecutorTest {

public static void main(String[] args) {

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);

for (int i = 0; i < 10; i++) {

final int index = i;

fixedThreadPool.execute(new Runnable() {

public void run() {

try {

System.out.println(index);

Thread.sleep(2000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

});

}

}

}

因为线程池大小为3,每个任务输出index后sleep 2秒,所以每两秒打印3个数字。

定长线程池的大小最好根据系统资源进行设置。如Runtime.getRuntime().availableProcessors()

newScheduledThreadPool

创建一个定长线程池,支持定时及周期性任务执行。延迟执行示例代码如下:

public class ThreadPoolExecutorTest {

public static void main(String[] args) {

ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);

scheduledThreadPool.schedule(new Runnable() {

public void run() {

System.out.println("delay 3 seconds");

}

}, 3, TimeUnit.SECONDS);

}

}

表示延迟3秒执行。

定期执行示例代码如下:

public class ThreadPoolExecutorTest {

public static void main(String[] args) {

ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);

scheduledThreadPool.scheduleAtFixedRate(new Runnable() {

public void run() {

System.out.println("delay 1 seconds, and excute every 3 seconds");

}

}, 1, 3, TimeUnit.SECONDS);

}

}

表示延迟1秒后每3秒执行一次。

newSingleThreadExecutor

public class ThreadPoolExecutorTest {

public static void main(String[] args) {

ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();

for (int i = 0; i < 10; i++) {

final int index = i;

singleThreadExecutor.execute(new Runnable() {

public void run() {

try {

System.out.println(index);

Thread.sleep(2000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

});

}

}

}

这里只是简单叙述了一下线程的管理的各种方法,后续还会针对 锁 进行讲解

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值