使用多線程用new Thread():
1.多任務情況下,避免線程頻繁的創(chuàng)建銷毀;
2.多個線程頻繁的創(chuàng)建會占用大量的資源,并且在資源競爭的時候出現問題,缺乏統(tǒng)一的管理,容易造成線程卡頓;
3.多個線程頻繁銷毀,會頻繁調用GC機制,降低性能并且耗時;
線程池的作用:
1.對線程統(tǒng)一管理,避免資源競爭造成卡頓、死機等問題;
2.對線程服用,不會在線程結束后立即銷毀,等待其他任務。避免了頻繁創(chuàng)建、銷毀和調用GC機制
public class ThreadPool {
ThreadPoolExecutor mThreadPoolExecutor;
private int corePoolSize;
private int maximumPoolSize;
private long keepAliveTime;
private static ThreadPool mThreadPool = null;
public static ThreadPool getInstance() {
if (mThreadPool == null) {
synchronized (ThreadPool.class){
mThreadPool = new ThreadPool(5, 10, 5 * 1000);
}
}
return mThreadPool;
}
private ThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime) {
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.keepAliveTime = keepAliveTime;
}
private ThreadPoolExecutor initExecutor() {
if (mThreadPoolExecutor == null) {
synchronized (ThreadPool.class) {
if (mThreadPoolExecutor == null) {
TimeUnit unit = TimeUnit.MILLISECONDS;
ThreadFactory threadFactory = Executors.defaultThreadFactory();
RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();
mThreadPoolExecutor = new ThreadPoolExecutor(
corePoolSize,//核心線程數
maximumPoolSize,//最大線程數
keepAliveTime,//保持時間
unit,//保持時間對應的單位
workQueue,
threadFactory,//線程工廠
handler);//異常捕獲器
}
}
}
return mThreadPoolExecutor;
}
/**
* 執(zhí)行任務
*/
public void executeTask(Runnable r) {
initExecutor();
mThreadPoolExecutor.execute(r);
}
/**
* 提交任務
*/
public Future<?> commitTask(Runnable r) {
initExecutor();
return mThreadPoolExecutor.submit(r);
}
/**
* 刪除任務
*/
public void removeTask(Runnable r) {
initExecutor();
mThreadPoolExecutor.remove(r);
}
}
FutureTask
FutureTask是實現了future的Runable,FutureTask比Runable多了一個執(zhí)行的返回值
private void test(){
AsyncTask<Boolean,String,Integer> asyncTask = new AsyncTask<Boolean, String, Integer>() {
@Override
protected Integer doInBackground(Boolean... booleans) {
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
@Override
protected void onCancelled(Integer integer) {
super.onCancelled(integer);
}
@Override
protected void onCancelled() {
super.onCancelled();
}
};
asyncTask.execute();
asyncTask.getStatus();
Callable<Boolean> callable = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return false;
}
};
FutureTask futureTask = new FutureTask(callable );
futureTask.cancel(true);
ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
2,10,300,
TimeUnit.MICROSECONDS,new LinkedBlockingDeque<Runnable>(),
Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
Future<Boolean> future= poolExecutor.submit(callable);
future.cancel(true);
}