介绍new thread的弊端及java四种线程池的使用,对android同样适用。本文是基础篇,后面会分享下线程池一些高级功能。
1、new thread的弊端
执行一个异步任务你还只是如下new thread吗?
java
1
2
3
4
5
6
7
new thread(new runnable() {
@override
public void run() {
// todo auto-generated method stub
}
}).start();
那你就out太多了,new thread的弊端如下:
a. 每次new thread新建对象性能差。
b. 线程缺乏统一管理,可能无限制新建线程,相互之间竞争,及可能占用过多系统资源导致死机或oom。
c. 缺乏更多功能,如定时执行、定期执行、线程中断。
相比new thread,java提供的四种线程池的好处在于:
a. 重用存在的线程,减少对象创建、消亡的开销,性能佳。
b. 可有效控制最大并发线程数,提高系统资源的使用率,同时避免过多资源竞争,避免堵塞。
c. 提供定时执行、定期执行、单线程、并发数控制等功能。
2、java 线程池
java通过executors提供四种线程池,分别为:
newcachedthreadpool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
newfixedthreadpool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
newscheduledthreadpool 创建一个定长线程池,支持定时及周期性任务执行。
newsinglethreadexecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(fifo, lifo, 优先级)执行。
(1). newcachedthreadpool
创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。示例代码如下:
8
9
10
11
12
13
14
15
16
17
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() {
system.out.println(index);
});
线程池为无限大,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程。
(2). newfixedthreadpool
创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。示例代码如下:
executorservice fixedthreadpool = executors.newfixedthreadpool(3);
fixedthreadpool.execute(new runnable() {
thread.sleep(2000);
// todo auto-generated catch block
因为线程池大小为3,每个任务输出index后sleep 2秒,所以每两秒打印3个数字。
(3) newscheduledthreadpool
创建一个定长线程池,支持定时及周期性任务执行。延迟执行示例代码如下:
scheduledexecutorservice scheduledthreadpool = executors.newscheduledthreadpool(5);
scheduledthreadpool.schedule(new runnable() {
system.out.println("delay 3 seconds");
}, 3, timeunit.seconds);
表示延迟3秒执行。
定期执行示例代码如下:
scheduledthreadpool.scheduleatfixedrate(new runnable() {
system.out.println("delay 1 seconds, and excute every 3 seconds");
}, 1, 3, timeunit.seconds);
表示延迟1秒后每3秒执行一次。
scheduledexecutorservice比timer更安全,功能更强大,后面会有一篇单独进行对比。
(4)、newsinglethreadexecutor
创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(fifo, lifo, 优先级)执行。示例代码如下:
executorservice singlethreadexecutor = executors.newsinglethreadexecutor();
singlethreadexecutor.execute(new runnable() {
结果依次输出,相当于顺序执行各个任务。
from:http://www.trinea.cn/android/java-android-thread-pool/
欢迎加群互相学习,共同进步。qq群:ios: 58099570 | android: 330987132 | go:217696290 | python:336880185 | 做人要厚道,转载请注明出处!http://www.cnblogs.com/sunshine-anycall/p/4755275.html