线程池
使用线程池的好处:
1.重用线程池中的线程,避免因为线程的创建和销毁所带来的性能的开销。
2.能有效的控制线程池的最大并发数,避免因为大量的线程之间因相互抢占资源而导致的阻塞现象。
3.可以对线程进行简单的管理,并提供定时执行以及指定间隔循环执行等功能。
使用AtomicInteger提供原子性操作的Integer的类,通过线程安全的方式进行加减
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadPool {
int maxCount = 3;
AtomicInteger count =new AtomicInteger(0);// 当前开的线程数 count=0
LinkedList<Runnable> runnables = new LinkedList<Runnable>();
public void execute(Runnable runnable) {
runnables.add(runnable);
if(count.incrementAndGet()<=3){
createThread();// 最大开三个线程
}
}
private void createThread() {
new Thread() {
@Override
public void run() {
super.run();
while (true) {
// 取出来一个异步任务
if (runnables.size() > 0) {
Runnable remove = runnables.remove(0); //在集合中移除第一个对象 返回值正好是移除的对象
if (remove != null) {
remove.run();
}
}else{
// 等待状态 wake();
}
}
}
}.start();
}
}
在写程序时有些异步程序只执行一遍就不需要了,为了方便经常会写下面的代码
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
}
}).start();
这样new出来的匿名对象会存在一些问题
1.由于是匿名的,无法对它进行管理
2.如果需要多次执行这个操作就new多次,可能创建多个,占用系统资源
3.无法执行更多的操作
使用线程池的好处
1.可以重复利用存在的线程,减少系统因为线程的 创建和销毁带来的性能的开销
2.利用线程池可以执行定时、并发数的控制,避免大量线程之间因相互抢占资源而导致的阻塞现象
ThreadManager.java线程池来管理线程
package com.ldw.marketm.thread;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Created by ldw on 2018/5/12.
*/
/*
* 线程管理,线程池
*/
public class ThreadManager {
//构造方法
private ThreadManager() {
}
//线程管理者
private static ThreadManager instance = new ThreadManager();
private ThreadPoolProxy longPool;
private ThreadPoolProxy shortPool;
public static ThreadManager getInstance() {
return instance;
}
//联网耗时
//创建一个线程池
public synchronized ThreadPoolProxy createLongPool() {
if (longPool == null) {
longPool = new ThreadPoolProxy(5, 5, 5000L);
}
return longPool;
}
//创建一个线程池
public synchronized ThreadPoolProxy createShortPool() {
if (shortPool == null) {
ThreadPoolProxy shortPool = new ThreadPoolProxy(3, 3, 5000L);
}
return shortPool;
}
public class ThreadPoolProxy {
//java提供的线程池
private ThreadPoolExecutor pool;
private int corePoolSize;//线程池中线程的大小
private int maximumPoolSize;
private long time;//线程存活的时间
//构造方法,初始化线程池的大小
public ThreadPoolProxy(int corePoolSize, int maximumPoolSize, long time) {
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.time = time;
}
/**
* 执行任务
*
* @param runnable
*/
public void execute(Runnable runnable) {
//如果线程池是空的,创建线程池
if (pool == null) {
// 创建线程池
/*
* 1. 线程池里面管理多少个线程2. 如果排队满了, 额外的开的线程数3. 如果线程池没有要执行的任务 存活多久4.
* 时间的单位 5 如果 线程池里管理的线程都已经用了,剩下的任务 临时存到LinkedBlockingQueue对象中 排队
*/
pool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
time, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(10));
}
// 调用线程池 执行异步任务
pool.execute(runnable);
}
/**
* 取消任务
*
* @param runnable
*/
public void cancel(Runnable runnable) {
//线程池不为空,没有崩溃也没有停止
if (pool != null && !pool.isShutdown() && !pool.isTerminated()) {
pool.remove(runnable); // 取消异步任务
}
}
}
}
ThreadManager线程池的使用
//开启一个子线程,在子线程中请求数据
//利用线程池管理线程
ThreadManager.getInstance().createLongPool().execute(new Runnable() {
@Override
public void run() {
SystemClock.sleep(1000);//休息2s显示加载中的页面
//请求服务器返回数据
final LoadResult result = load();
//防止很快的退出了activity,activity为空,子线程却依旧在运行的情况,下面的getActivity.runOnUiThread会出错
if(getActivity() != null){
//数据请求完成以后在主线程中刷新UI
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if(result != null){
//更新状态
state = result.getValue();
showPage();//更新显示的界面,一般用来过渡加载中的页面
}
}
});
}
}
});
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
/**
* 定长线程池,可做延时
*/
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
只创建了一个线程