1. 程式人生 > 其它 >Java 執行緒與執行緒池進階

Java 執行緒與執行緒池進階

1. 執行緒的狀態

  Java程式在執行過程中執行緒可能有6種狀態:

  • New:新建立狀態;
  • Runnable:可執行狀態;
  • Blocked:阻塞狀態;
  • Waiting:等待狀態;
  • Timed waiting:超時等待狀態;
  • Terminated:終止狀態;

2. 執行緒同步

  1. 加鎖與條件變數

    • Lock/Unlock:Java程式碼實現的工具類。
    • 重入鎖 ReentrantLock:Java 5 引入的,重入鎖表示該鎖支援一個執行緒對資源可以重複加鎖。

  2. Synchronized

    分類鎖與物件鎖

  3. Volatile

3. 阻塞佇列

  1. 什麼是阻塞佇列

  阻塞佇列常用於生產者與消費者場景,生產者是往佇列裡新增元素的執行緒,消費者是從佇列裡拿元素的執行緒。阻塞佇列就是生產者存放元素的容器,消費者就是從容器中拿元素的。

  2. 阻塞佇列的常見使用場景

    1. 當佇列中沒有資料,消費者的執行緒會自動阻塞(掛起),直到有資料新增到佇列中消費者執行緒才會被喚醒。

    2. 當佇列中填滿資料,生產者的執行緒會自動阻塞(掛起),直到佇列中有空位置,生產者執行緒才會被喚醒。

  以上兩種阻塞場景使用的佇列就是阻塞佇列。

  3. Java中的阻塞佇列

  • ArrayBlockingQueue:由陣列結構組成的有界阻塞佇列。
  • LinkedBlockingQueue:由連結串列結構組成的有界阻塞佇列。
  • PriorityBlockingQueue:支援優先順序排序的無界阻塞佇列。
  • DelayQueue:使用優先順序佇列實現的無界阻塞佇列。
  • SynchronousQueue:不儲存元素的阻塞佇列。
  • LinkedTransferQueue:由連結串列結構組成的無界阻塞佇列。
  • LinkedBlockingDeue:由連結串列結構組成的雙向阻塞佇列。

4. 執行緒池

  Java 中執行緒池工具類:ThreadPoolExecutor:Android 執行緒池ThreadPoolExecutor類

  1. 常用執行緒池的種類

  通過直接或者間接配置ThreadPoolExecutor執行緒池類的引數可以建立不同型別的執行緒池。

    • FixedThreadPool;
    • CacheThreadPool;
    • SingleThreadExecutor;
    • ScheduledThreadPool;

  2. FixedThreadPool:是可重用固定執行緒數的執行緒池。

    /**
     * Creates a thread pool that reuses a fixed number of threads
     * operating off a shared unbounded queue, using the provided
     * ThreadFactory to create new threads when needed.  At any point,
     * at most {@code nThreads} threads will be active processing
     * tasks.  If additional tasks are submitted when all threads are
     * active, they will wait in the queue until a thread is
     * available.  If any thread terminates due to a failure during
     * execution prior to shutdown, a new one will take its place if
     * needed to execute subsequent tasks.  The threads in the pool will
     * exist until it is explicitly {@link ExecutorService#shutdown
     * shutdown}.
     *
     * @param nThreads the number of threads in the pool
     * @param threadFactory the factory to use when creating new threads
     * @return the newly created thread pool
     * @throws NullPointerException if threadFactory is null
     * @throws IllegalArgumentException if {@code nThreads <= 0}
     */
    public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>(),
                                      threadFactory);
    }

  2. CachedThreadPool:根據需要建立執行緒的執行緒池,使用的阻塞佇列是無儲存的阻塞佇列。

    /**
     * Creates a thread pool that creates new threads as needed, but
     * will reuse previously constructed threads when they are
     * available.  These pools will typically improve the performance
     * of programs that execute many short-lived asynchronous tasks.
     * Calls to {@code execute} will reuse previously constructed
     * threads if available. If no existing thread is available, a new
     * thread will be created and added to the pool. Threads that have
     * not been used for sixty seconds are terminated and removed from
     * the cache. Thus, a pool that remains idle for long enough will
     * not consume any resources. Note that pools with similar
     * properties but different details (for example, timeout parameters)
     * may be created using {@link ThreadPoolExecutor} constructors.
     *
     * @return the newly created thread pool
     */
    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

  

  3. SingleThreadExecutor:單執行緒的執行緒池,只有一個核心執行緒。

    /**
     * Creates an Executor that uses a single worker thread operating
     * off an unbounded queue. (Note however that if this single
     * thread terminates due to a failure during execution prior to
     * shutdown, a new one will take its place if needed to execute
     * subsequent tasks.)  Tasks are guaranteed to execute
     * sequentially, and no more than one task will be active at any
     * given time. Unlike the otherwise equivalent
     * {@code newFixedThreadPool(1)} the returned executor is
     * guaranteed not to be reconfigurable to use additional threads.
     *
     * @return the newly created single-threaded Executor
     */
    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

  4. ScheduledThreadPool:一個能實現定時和週期性任務的執行緒池。

    /**
     * Creates a thread pool that can schedule commands to run after a
     * given delay, or to execute periodically.
     * @param corePoolSize the number of threads to keep in the pool,
     * even if they are idle
     * @return a newly created scheduled thread pool
     * @throws IllegalArgumentException if {@code corePoolSize < 0}
     */
    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }