Java并發(fā)之串行線程池實(shí)例解析

這篇文章主要介紹了Java并發(fā)之串行線程池實(shí)例解析,分享了相關(guān)代碼示例,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下

前言

做Android的這兩年時(shí)間,通過(guò)研究Android源碼,也會(huì)Java并發(fā)處理多線程有了自己的一些理解。

那么問(wèn)題來(lái)了,如何實(shí)現(xiàn)一個(gè)串行的線程池呢?

思路

何為串行線程池呢?

也就是說(shuō),我們的Runnable對(duì)象應(yīng)該有個(gè)排隊(duì)的機(jī)制,它們順序從隊(duì)列尾部進(jìn)入,并且從隊(duì)列頭部選擇Runnable進(jìn)行執(zhí)行。

既然我們有了思路,那我們就考慮一下所需要的數(shù)據(jù)結(jié)構(gòu)?

既然是從隊(duì)列尾部插入Runnable對(duì)象,從隊(duì)列頭部執(zhí)行Runnable對(duì)象,我們自然需要一個(gè)隊(duì)列。Java的SDK已經(jīng)給我們提供了很好的隊(duì)列數(shù)據(jù)結(jié)構(gòu),例如雙端隊(duì)列:ArrayDeque<Runnable>。
?因?yàn)樯婕暗骄€程的執(zhí)行,那我們首先就需要有一個(gè)合適的線程池,使用ThreadPoolExecutor類(lèi)即可構(gòu)造。
?既然是串行執(zhí)行,那如何保持串行機(jī)制呢?我們可以通過(guò)try和finally機(jī)制,我們將傳入的Runnable對(duì)象重新封裝成一個(gè)新的Runnable對(duì)象,在新的Runnable的run方法的try塊中執(zhí)行Runnable的run方法,在finally中調(diào)用執(zhí)行隊(duì)列頭部Runnable對(duì)象出隊(duì)列,并放入線程池執(zhí)行的方法。

示例代碼

import java.util.ArrayDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
 
/**
 * Created by wzy on 16-1-5.
 */
public class SerialExecutor {
  private Runnable mActive;
  private ArrayDeque<Runnable> mArrayDeque = new ArrayDeque<>();
 
  private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
  private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
  private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
  private static final int KEEP_ALIVE = 1;
  private static final BlockingQueue<Runnable> sPoolWorkQueue =
      new LinkedBlockingDeque<>(128);
  private static final ThreadFactory sThreadFactory = new ThreadFactory() {
    private final AtomicInteger mCount = new AtomicInteger(1);
    @Override
    public Thread newThread(Runnable r) {
      return new Thread(r, "Serial thread #" + mCount.getAndIncrement());
    }
  };
  private static final ThreadPoolExecutor THREAD_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE,
      MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
 
  public synchronized void execute(final Runnable r) {
    mArrayDeque.offer(new Runnable() {
      @Override
      public void run() {
        try {
          r.run();
        } finally {
          scheduleNext();
        }
      }
    });
    // 第一次入隊(duì)列時(shí)mActivie為空,因此需要手動(dòng)調(diào)用scheduleNext方法
    if (mActive == null) {
      scheduleNext();
    }
  }
 
  private void scheduleNext() {
    if ((mActive = mArrayDeque.poll()) != null) {
      THREAD_EXECUTOR.execute(mActive);
    }
  }
 
  public static void main(String[] args) {
    SerialExecutor serialExecutor = new SerialExecutor();
    for (int i = 0; i < 10; i ++) {
      final int j = i;
      serialExecutor.execute(new Runnable() {
        @Override
        public void run() {
          System.out.println("The num is :" + (j + 1));
          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      });
    }
  }
}

執(zhí)行結(jié)果如下:

The num is :1
 The num is :2
 The num is :3
 The num is :4
 The num is :5
 The num is :6
 The num is :7
 The num is :8
 The num is :9
 The num is :10

總結(jié)

以上就是本文關(guān)于Java并發(fā)之串行線程池實(shí)例解析的全部?jī)?nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專(zhuān)題,如有不足之處,歡迎留言指出。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容