android实现高性能,高并发,可延时线程池管理
为什么要使用线程池?
1.)new Thread()的缺点
- 每次new Thread()耗费性能
- 调用new Thread()创建的线程缺乏管理,被称为野线程,而且可以无限制创建,之间相互竞争,会导致过多占用系统资源导致系统瘫痪。
- 不利于扩展,比如如定时执行、定期执行、线程中断
2.)采用线程池的优点
- 重用存在的线程,减少对象创建、消亡的开销,性能佳
- 可有效控制最大并发线程数,提高系统资源的使用率,同时避免过多资源竞争,避免堵塞
- 提供定时执行、定期执行、单线程、并发数控制等功能
线程池实现:
1.实现思路:
使用生产者消费者模式进行设计:通过应用层给线程池提供 线程队列(生产者),线程池执行线程队列(消费者)
由线程池设定最大线程数,当在排队的线程数超过线程池最大数量,线程池会拒绝执行,被拒绝执行的线程将被从新
放入线程队列进行排队
生产者:线程队列(阻塞队列)
消费者:线程池
拒绝机制:当排队的线程进入线程池被拒绝后,重新放入队列,重新排队
设计思路
具体代码实现:
ThreadPoolManager:
public class ThreadPoolManager {
private static ThreadPoolManager instance=new ThreadPoolManager();
public static ThreadPoolManager getInstance() {
return instance;
}
private ThreadPoolExecutor threadPoolExecutor;
private LinkedBlockingQueue<Future<?>> service=new LinkedBlockingQueue<>();
private ThreadPoolManager(){
threadPoolExecutor=new ThreadPoolExecutor(4,10,10, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(4),handler);
threadPoolExecutor.execute(runnable);
}
private Runnable runnable=new Runnable() {
@Override
public void run() {
while (true) {
FutureTask futureTask = null;
try {
Log.e("myThreadPook","service size "+service.size());
futureTask = (FutureTask) service.take();
Log.e("myThreadPook","池 "+threadPoolExecutor.getPoolSize());
} catch (InterruptedException e) {
e.printStackTrace();
}
if (futureTask != null) {
threadPoolExecutor.execute(futureTask);
}
}
}
};
public <T> void execute(final FutureTask<T> futureTask, Object delayed){
if(futureTask!=null){
try {
if(delayed!=null){
Timer timer=new Timer();
timer.schedule(new TimerTask(){
public void run(){
try {
service.put(futureTask);
} catch (InterruptedException e) {
e.printStackTrace();
}
}},(long)delayed);
}else {
service.put(futureTask);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private RejectedExecutionHandler handler=new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) {
try {
service.put(new FutureTask<Object>(runnable,null));//
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}
应用层调用:
MainActivity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int i=0;i<100;i++){//高并发
final int finalI = i;
Thread thread =new Thread(){
@Override
public void run() {
super.run();
// Log.e("jjjjjj", "runnable---->"+ finalI);
}
};
ThreadPoolManager.getInstance().execute(new FutureTask<Object>(thread,null),null);
}
Thread thread =new Thread(){
@Override
public void run() {
super.run();
Log.e("jjjjjj", "runnable---->finalIrunnable");
}
};
ThreadPoolManager.getInstance().execute(new FutureTask<Object>(thread,null),(long)10000);//延时执行
}
}