创建指定线程数量的线程池
private static ExecutorService scheduledTaskFactoryExecutor = null; private boolean isCancled = false; private static class ThreadFactoryTest implements ThreadFactory {
@Override public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setName(TAG); //通过Thread.setDaemon(false)设置为用户线程;通过Thread.setDaemon(true)设置为守护线程 //主线程结束后用户线程还会继续运行,JVM存活;主线程结束后守护线程和JVM的状态又下面第2条确定 //如果没有用户线程,都是守护线程,那么JVM结束(随之而来的是所有的一切烟消云散,包括所有的守护线程) //安卓程序退出后jvm会被回收掉,而java程序基于服务的退出后jvm不会立马回收 thread.setDaemon(true); return thread; } }
static { scheduledTaskFactoryExecutor = Executors.newFixedThreadPool(3, new ThreadFactoryTest()); scheduledTaskFactoryExecutor.submit(new Runnable() { @Override public void run() { Log.i(TAG, "This is the ThreadFactory Test submit Run! ! ! "); } }); }
AsyncTaskTest task = new AsyncTaskTest(url);
//把定义好的线程在线程池执行
task.executeOnExecutor(scheduledTaskFactoryExecutor); mTaskList.add(task);
class AsyncTaskTest extends AsyncTask{//异步任务 private String url; public AsyncTaskTest(String url) { this.url = url; } @Override protected Void doInBackground(Void... params) { if (!isCancelled() && isCancled == false) // 这个地方很关键,如果不设置标志位的话,直接setCancel(true)是无效的 { Bitmap bmp; if (!url.contains("http")) { //表示网络图片 bmp = ImageLoader.getInstance().loadImageSync("file://" + url, options); } else { bmp = ImageLoader.getInstance().loadImageSync(url, options); } if (bmp != null) { byte[] b = new byte[0]; try { b = MyImageUtil.getImageThumbnailBase(bmp); upload(b); publishProgress(count); // 更新进度条 } catch (IOException e) { UMDocApplication.getInstance().getLog().e(e); } Log.d(TAG, "byte length " + b.length); } } return null; } @Override protected void onProgressUpdate(Integer... values) { Log.d(TAG, "count " + values[0]); if (values[0] == 1) proBar.setVal(count); } }