android中的线程池 怎么用
2个回答
展开全部
Java的线程池对Android也是适用的
线程池的作用:
线程池作用就是限制系统中执行线程的数量。
根据系统的环境情况,可以自动或手动设置线程数量,达到运行的最佳效果;少了浪费了系统资源,多了造成系统拥挤效率不高。用线程池控制线程数量,其他线程
排队等候。一个任务执行完毕,再从队列的中取最前面的任务开始执行。若队列中没有等待进程,线程池的这一资源处于等待。当一个新任务需要运行时,如果线程
池中有等待的工作线程,就可以开始运行了;否则进入等待队列。
为什么要用线程池:
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 < 50; i++) {
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 = 11 index = 30
active count = 11 index = 31
active count = 11 index = 32
active count = 11 index = 33
active count = 11 index = 34
active count = 11 index = 35
active count = 11 index = 36
active count = 11 index = 37
active count = 11 index = 38
active count = 11 index = 39
active count = 11 index = 40
active count = 11 index = 41
active count = 11 index = 42
active count = 11 index = 43
active count = 11 index = 44
active count = 11 index = 45
active count = 11 index = 46
active count = 11 index = 47
active count = 11 index = 48
active count = 10 index = 49
从打印消息来看开始线程数在增加,后来稳定,可以修改休眠时间,休眠时间越短创建的线程数就越多,因为前面的还没执行完,线程池中没有可以执行的就需要创建;如果把休眠时间加大,创建的线程数就会少
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
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* 定长线程池,可做延时
*/
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);
}
打印结果
?
1
2
3
4
5
6
7
8
9
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这个最简单
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 单例线程
*/
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();
}
}
});
}
}
打印结果:
?
1
2
3
4
5
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
线程池的作用:
线程池作用就是限制系统中执行线程的数量。
根据系统的环境情况,可以自动或手动设置线程数量,达到运行的最佳效果;少了浪费了系统资源,多了造成系统拥挤效率不高。用线程池控制线程数量,其他线程
排队等候。一个任务执行完毕,再从队列的中取最前面的任务开始执行。若队列中没有等待进程,线程池的这一资源处于等待。当一个新任务需要运行时,如果线程
池中有等待的工作线程,就可以开始运行了;否则进入等待队列。
为什么要用线程池:
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 < 50; i++) {
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 = 11 index = 30
active count = 11 index = 31
active count = 11 index = 32
active count = 11 index = 33
active count = 11 index = 34
active count = 11 index = 35
active count = 11 index = 36
active count = 11 index = 37
active count = 11 index = 38
active count = 11 index = 39
active count = 11 index = 40
active count = 11 index = 41
active count = 11 index = 42
active count = 11 index = 43
active count = 11 index = 44
active count = 11 index = 45
active count = 11 index = 46
active count = 11 index = 47
active count = 11 index = 48
active count = 10 index = 49
从打印消息来看开始线程数在增加,后来稳定,可以修改休眠时间,休眠时间越短创建的线程数就越多,因为前面的还没执行完,线程池中没有可以执行的就需要创建;如果把休眠时间加大,创建的线程数就会少
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
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* 定长线程池,可做延时
*/
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);
}
打印结果
?
1
2
3
4
5
6
7
8
9
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这个最简单
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 单例线程
*/
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();
}
}
});
}
}
打印结果:
?
1
2
3
4
5
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
展开全部
//在Android中实现线程池,首先需要实现一个线程工厂(ThreadFactory)的子类,具体实现方式如下所示(PriorityThreadFactory.Java):
import android.os.Process;
/**
* A thread factory that create threads with a given thread priority
* @author jony
* @version 1.0
*/
public class PriorityThreadFactory implements ThreadFactory{
private final String mName;
private final int mPriority;
private final AtomicInteger mNumber = new AtomicInteger();
public PriorityThreadFactory(String name, int priority) {
mName = name;// 线程池的名称
mPriority = priority;//线程池的优先级
}
@Override
public Thread newThread(Runnable r) {
return new Thread(r, mName +"-"+mNumber.getAndIncrement()){
@Override
public void run() {
// 设置线程的优先级
Process.setThreadPriority(mPriority);
super.run();
}
};
}
}
//以上是创建线程池的一个工具类,接下来为大家介绍本篇文章的重点,线程池的实现方式,具体实现方式如下所示(MyThreadPool.java):
package com.tcl.actionbar;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
package com.tcl.actionbar;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ThreadFactory;
// 线程池的实现方式
public class MyThreadPool {
private final static int POOL_SIZE = 4;// 线程池的大小最好设置成为CUP核数的2N
private final static int MAX_POOL_SIZE = 6;// 设置线程池的最大线程数
private final static int KEEP_ALIVE_TIME = 4;// 设置线程的存活时间
private final Executor mExecutor;
public MyThreadPool() {
// 创建线程池工厂
ThreadFactory factory = new PriorityThreadFactory("thread-pool", android.os.Process.THREAD_PRIORITY_BACKGROUND);
// 创建工作队列
BlockingQueue<Runnable> workQueue = new LinkedBlockingDeque<Runnable>();
mExecutor = new ThreadPoolExecutor(POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS, workQueue, factory);
}
// 在线程池中执行线程
public void submit(Runnable command){
mExecutor.execute(command);
}
}
//自己觉得这个·代码不错,我就只是将它搬了过来,实际代码地址:http://blog.csdn.net/weihan1314/article/details/7983725
import android.os.Process;
/**
* A thread factory that create threads with a given thread priority
* @author jony
* @version 1.0
*/
public class PriorityThreadFactory implements ThreadFactory{
private final String mName;
private final int mPriority;
private final AtomicInteger mNumber = new AtomicInteger();
public PriorityThreadFactory(String name, int priority) {
mName = name;// 线程池的名称
mPriority = priority;//线程池的优先级
}
@Override
public Thread newThread(Runnable r) {
return new Thread(r, mName +"-"+mNumber.getAndIncrement()){
@Override
public void run() {
// 设置线程的优先级
Process.setThreadPriority(mPriority);
super.run();
}
};
}
}
//以上是创建线程池的一个工具类,接下来为大家介绍本篇文章的重点,线程池的实现方式,具体实现方式如下所示(MyThreadPool.java):
package com.tcl.actionbar;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
package com.tcl.actionbar;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ThreadFactory;
// 线程池的实现方式
public class MyThreadPool {
private final static int POOL_SIZE = 4;// 线程池的大小最好设置成为CUP核数的2N
private final static int MAX_POOL_SIZE = 6;// 设置线程池的最大线程数
private final static int KEEP_ALIVE_TIME = 4;// 设置线程的存活时间
private final Executor mExecutor;
public MyThreadPool() {
// 创建线程池工厂
ThreadFactory factory = new PriorityThreadFactory("thread-pool", android.os.Process.THREAD_PRIORITY_BACKGROUND);
// 创建工作队列
BlockingQueue<Runnable> workQueue = new LinkedBlockingDeque<Runnable>();
mExecutor = new ThreadPoolExecutor(POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS, workQueue, factory);
}
// 在线程池中执行线程
public void submit(Runnable command){
mExecutor.execute(command);
}
}
//自己觉得这个·代码不错,我就只是将它搬了过来,实际代码地址:http://blog.csdn.net/weihan1314/article/details/7983725
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询