線程池的簡單使用,線程池簡單使用

來源:互聯網
上載者:User

線程池的簡單使用,線程池簡單使用

建立指定線程數量的線程池

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<Void, Integer, Void> {//非同步任務

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);
}

}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.