Java 线程与线程池进阶

2021/8/28 17:06:11

本文主要是介绍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);
    }

 

    

  

 



这篇关于Java 线程与线程池进阶的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程