Android线程池简单使用
生活随笔
收集整理的這篇文章主要介紹了
Android线程池简单使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
線程池使用的好處:
1)對多個線程進行統一地管理,避免資源競爭中出現的問題。
2)對線程進行復用,線程在執行完任務后不會立刻銷毀,而會等待另外的任務,這樣就不會頻繁地創建、銷毀線程和調用GC。
使用ThreadPoolExecutor創建基本線程池,構造方法:
public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue) {this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,Executors.defaultThreadFactory(), defaultHandler);
}
//示例1
final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, //核心線程數10, //最大線程數量60,// 空閑線程等待時間TimeUnit.SECONDS, //時間單位new ArrayBlockingQueue<Runnable>(100));Runnable runnable = new Runnable() {@Overridepublic void run() {//... 耗時操作}};threadPoolExecutor.execute(runnable);
//示例2
private val cacheThread: ExecutorService by lazy { ThreadPoolExecutor(Runtime.getRuntime().availableProcessors() * 30, Runtime.getRuntime().availableProcessors() * 50,600L, TimeUnit.SECONDS,SynchronousQueue<Runnable>()); }
//示例3
public class MyThreadFactory implements ThreadFactory {private int counter;private String name;public MyThreadFactory(String name) {counter = 0;this.name = name;}@Overridepublic Thread newThread(Runnable run) {Thread thread = new Thread(run, name + "-Thread-" + counter);counter++;Timber.d("create thread with name: %s", thread.getName());return thread;}
}public class MyExecutor extends ThreadPoolExecutor {public MyExecutor(String threadPrefix) {super(2, 6, 60,TimeUnit.SECONDS, new ArrayBlockingQueue<>(3),new MyThreadFactory(threadPrefix),new DiscardOldestPolicy());}public static ThreadPoolExecutor polling = new MyExecutor("polling");public static ThreadPoolExecutor backgroundTask = new MyExecutor("backgroundTask");}
以下是使用:
MyExecutor.polling.execute {doStatus()
}MyExecutor.polling.execute {cleanDb()
}MyExecutor.polling.shutdownNow()
總結
以上是生活随笔為你收集整理的Android线程池简单使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Glide的缓存机制
- 下一篇: 介绍一下android的事件分发机制