JAVA 线程优化及线程池管理

一:优化HandlerThread

我们在 activity中start了一个HandlerThread,那么这个线程会启动一个looper消息循环,当activity退出了,这个HandlerThread线程并没有终止,还是在那里做looper死循环,如果页面跳转频繁重复,这样的无用线程会越来越多,占用系统资源,最终导致进程crash掉。

所以当HandlerThread已经没有利用价值的时候,将它停止掉,只有这样才能开发出健壮的android程序。

首先知道如何停止一个已经启动了的HandlerThread呢?

先看 Looper.loop()的核心代码:

[java]  view plain  copy
  1. while (true) {  
  2.     Message msg = queue.next(); // might block  
  3.     if (msg != null) {  
  4.         if (msg.target == null) {  
  5.             // No target is a magic identifier for the quit message.  
  6.             return;  
  7.         }  
  8.   
  9.         long wallStart = 0;  
  10.         long threadStart = 0;  
  11.   
  12.         // This must be in a local variable, in case a UI event sets the logger  
  13.         Printer logging = me.mLogging;  
  14.         if (logging != null) {  
  15.             logging.println(">>>>> Dispatching to " + msg.target + " " +  
  16.                     msg.callback + ": " + msg.what);  
  17.             wallStart = SystemClock.currentTimeMicro();  
  18.             threadStart = SystemClock.currentThreadTimeMicro();  
  19.         }  
  20.   
  21.         msg.target.dispatchMessage(msg);  

看到里面是一个无限循环,退出循环的条件是:msg.target == null;

也就是说,如果我们向此looper的MessageQueue发送一个target为null的message,就可以停止这个线程的远行。


继续看Looper.Java的代码:

会发现有一个方法:

[java]  view plain  copy
  1. public void quit() {  
  2.     Message msg = Message.obtain();  
  3.     // NOTE: By enqueueing directly into the message queue, the  
  4.     // message is left with a null target.  This is how we know it is  
  5.     // a quit message.  
  6.     mQueue.enqueueMessage(msg, 0);  
  7. }  
这个方法正是向MessageQueue发送了一个target为null的message!

所以,停止HandlerThread的方法终于找到了,就是使用quit方法,具体调用形式如下:

mHandlerThread.getLooper().quit();



二:线程池管理:

在时写异步程序只执行一遍就不需要了,为了方便经常会写下面的代码

new Thread(new Runnable() {
 
    @Override
    public void run() {
        // TODO Auto-generated method stub
    }
}).start();

这样new出来的匿名对象会存在一些问题

1.由于是匿名的,无法对它进行管理

2.如果需要多次执行这个操作就new多次,可能创建多个,占用系统资源

3.无法执行更多的操作

使用线程池的好处

1.可以重复利用存在的线程,减少系统的开销

2.利用线程池可以执行定时、并发数的控制

线程池的作用:

线程池作用就是限制系统中执行线程的数量。

原理:根据系统的环境情况,可以自动或手动设置线程数量,达到运行的最佳效果;少了浪费了系统资源,多了造成系统拥挤效率不高。用线程池控制线程数量,其他线程排队等候。一个任务执行完毕,再从队列的中取最前面的任务开始执行。若队列中没有等待进程,线程池的这一资源处于等待。当一个新任务需要运行时,如果线程池中有等待的工作线程,就可以开始运行了;否则进入等待队列。

为什么要用线程池:

1.减少了创建和销毁线程的次数,每个工作线程都可以被重复利用,可执行多个任务。

2.可以根据系统的承受能力,调整线程池中工作线线程的数目,防止因为消耗过多的内存,而把服务器累趴下(每个线程需要大约       1MB内存,线程开的越多,消耗的内存也就越大,最后死机)。


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

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

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

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

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

1. newCachedThreadPool
/**
	 * 可以缓存线程池
	 */
	public static void Function1() {
		ExecutorService executorService = Executors.newCachedThreadPool();
		for (int i = 0; i < 30; i++) {//30次
			final int index = i;
			try {
				Thread.sleep(100); // 休眠时间越短创建的线程数越多
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			executorService.execute(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					System.out.println("active count = " + Thread.activeCount()
							+ " index = " + index);
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			});
		}
	}

打印结果

active count = 2 index = 0

active count = 3 index = 1

active count = 4 index = 2

active count = 5 index = 3

active count = 6 index = 4

active count = 7 index = 5

active count = 8 index = 6

active count = 9 index = 7

active count = 10 index = 8

active count = 11 index = 9

active count = 11 index = 10

active count = 11 index = 11

active count = 11 index = 12

active count = 11 index = 13

active count = 11 index = 14

active count = 11 index = 15

active count = 11 index = 16

active count = 11 index = 17

active count = 11 index = 18

active count = 11 index = 19

active count = 11 index = 20

active count = 11 index = 21

active count = 11 index = 22

active count = 11 index = 23

active count = 11 index = 24

active count = 11 index = 25

active count = 11 index = 26

active count = 11 index = 27

active count = 11 index = 28

active count = 11 index = 29

active count = 10 index = 30

从打印消息来看开始线程数在增加,后来稳定,可以修改休眠时间,休眠时间越短创建的线程数就越多,因为前面的还没执行完,线程池中没有可以执行的就需要创建;如果把休眠时间加大,创建的线程数就会少

2.newFixedThreadPool  根据传入的参数创建线程数目

/**
	 * 定长线程池
	 */
	public static void Function2() {
		ExecutorService executorService = Executors.newFixedThreadPool(3);
		for (int i = 0; i < 30; i++) {
			final int index = i;
			executorService.execute(new Runnable() {
				@Override
				public void run() {
					try {
						System.out.println("index = " + index
								+ "  thread count = " + Thread.activeCount());
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			});
		}
	}

3.newScheduledThreadPool

/**
	 * 定长线程池,可做延时
	 */
	public static void Function3() {
		ScheduledExecutorService executorService = Executors
				.newScheduledThreadPool(5);
		executorService.schedule(new Runnable() {

			@Override
			public void run() {
				System.out.println("delay 3 seconds" + "  thread count = "
						+ Thread.activeCount());
			}
		}, 3, TimeUnit.SECONDS);
	}

	/**
	 * 定期执行,可以用来做定时器
	 */
	public static void Function4() {
		ScheduledExecutorService executorService = Executors
				.newScheduledThreadPool(3);
		executorService.scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {
				System.out
						.println("delay 1 seconds, and excute every 3 seconds"
								+ "  thread count = " + Thread.activeCount());
			}
		}, 1, 3, TimeUnit.SECONDS);
	}

打印结果

delay 1 seconds, and excute every 3 seconds  thread count = 2
delay 1 seconds, and excute every 3 seconds  thread count = 3
delay 1 seconds, and excute every 3 seconds  thread count = 4
delay 1 seconds, and excute every 3 seconds  thread count = 4
delay 1 seconds, and excute every 3 seconds  thread count = 4
delay 1 seconds, and excute every 3 seconds  thread count = 4
delay 1 seconds, and excute every 3 seconds  thread count = 4
delay 1 seconds, and excute every 3 seconds  thread count = 4
delay 1 seconds, and excute every 3 seconds  thread count = 4

4.newSingleThreadExecutor这个最简单

/**
	 * 单例线程
	 */
	public static void Function5() {
		ExecutorService singleThreadExecutor = Executors
				.newSingleThreadExecutor();
		for (int i = 0; i < 5; i++) {
			final int index = i;
			singleThreadExecutor.execute(new Runnable() {

				@Override
				public void run() {
					try {
						System.out.println("index = " + index
								+ "  thread count = " + Thread.activeCount());
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			});
		}
	}

打印结果:

index = 0  thread count = 2
index = 1  thread count = 2
index = 2  thread count = 2
index = 3  thread count = 2
index = 4  thread count = 2

只创建了一个线程


[java]  view plain  copy
  1. while (true) {  
  2.     Message msg = queue.next(); // might block  
  3.     if (msg != null) {  
  4.         if (msg.target == null) {  
  5.             // No target is a magic identifier for the quit message.  
  6.             return;  
  7.         }  
  8.   
  9.         long wallStart = 0;  
  10.         long threadStart = 0;  
  11.   
  12.         // This must be in a local variable, in case a UI event sets the logger  
  13.         Printer logging = me.mLogging;  
  14.         if (logging != null) {  
  15.             logging.println(">>>>> Dispatching to " + msg.target + " " +  
  16.                     msg.callback + ": " + msg.what);  
  17.             wallStart = SystemClock.currentTimeMicro();  
  18.             threadStart = SystemClock.currentThreadTimeMicro();  
  19.         }  
  20.   
  21.         msg.target.dispatchMessage(msg);  

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

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

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

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

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




[java]  view plain  copy
  1. while (true) {  
  2.     Message msg = queue.next(); // might block  
  3.     if (msg != null) {  
  4.         if (msg.target == null) {  
  5.             // No target is a magic identifier for the quit message.  
  6.             return;  
  7.         }  
  8.   
  9.         long wallStart = 0;  
  10.         long threadStart = 0;  
  11.   
  12.         // This must be in a local variable, in case a UI event sets the logger  
  13.         Printer logging = me.mLogging;  
  14.         if (logging != null) {  
  15.             logging.println(">>>>> Dispatching to " + msg.target + " " +  
  16.                     msg.callback + ": " + msg.what);  
  17.             wallStart = SystemClock.currentTimeMicro();  
  18.             threadStart = SystemClock.currentThreadTimeMicro();  
  19.         }  
  20.   
  21.         msg.target.dispatchMessage(msg);  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序邦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值