您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關Java并發之串行線程池的示例分析的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
何為串行線程池呢?
也就是說,我們的Runnable對象應該有個排隊的機制,它們順序從隊列尾部進入,并且從隊列頭部選擇Runnable進行執行。
既然我們有了思路,那我們就考慮一下所需要的數據結構?
既然是從隊列尾部插入Runnable對象,從隊列頭部執行Runnable對象,我們自然需要一個隊列。Java的SDK已經給我們提供了很好的隊列數據結構,例如雙端隊列:ArrayDeque<Runnable>。
因為涉及到線程的執行,那我們首先就需要有一個合適的線程池,使用ThreadPoolExecutor類即可構造。
既然是串行執行,那如何保持串行機制呢?我們可以通過try和finally機制,我們將傳入的Runnable對象重新封裝成一個新的Runnable對象,在新的Runnable的run方法的try塊中執行Runnable的run方法,在finally中調用執行隊列頭部Runnable對象出隊列,并放入線程池執行的方法。
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(); } } }); // 第一次入隊列時mActivie為空,因此需要手動調用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(); } } }); } } }
執行結果如下:
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
感謝各位的閱讀!關于“Java并發之串行線程池的示例分析”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。