1 线程池的原理和应用

1.1 Excutor: 执行者 – 顶层接口

image.png
线程池从功能上看,就是一个任务执行器
submit 方法 -> 有返回值,用 Future 封装
execute 方法 -> 无返回值
execute 方法抛异常可以在主线程中 catch 到。
submit 方法执行任务是捕捉不到异常的。

  1. public class Excutor1 {
  2. public static void main(String[] args) {
  3. Executor executor = Executors.newFixedThreadPool(5);
  4. for (int i = 0; i < 10; i++) {
  5. final int a = i;
  6. executor.execute(() -> {
  7. System.out.println(a);
  8. //try {
  9. int s = 1 / 0;
  10. System.out.println("-----------");
  11. // } catch (Exception e) {
  12. // System.out.println("异常" + e);
  13. //}
  14. });
  15. }
  16. }
  17. }
  18. //抛的异常可以在主线程中捕获到。

1.2 ExecutorService

image.png
shutdown():停止接收新任务,原来的任务继续执行
shutdownNow():停止接收新任务,原来的任务停止执行
awaitTermination(long timeOut, TimeUnit unit):当前线程阻塞:停止接收新任务,原来的任务继续执行


private static void test1() throws InterruptedException {
        AtomicInteger sum = new AtomicInteger(0);
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) {
            final int a = i;
            //和Executor 的execute方法一样
            executorService.execute(() -> {
                System.out.println(a);
                sum.incrementAndGet();
            });
        }
        executorService.shutdown();
        //Thread.sleep(2000);
        //executorService.awaitTermination(10, TimeUnit.SECONDS);
        // executorService.shutdownNow();
        System.out.println("==========sum:" + sum.get());

    }

//shutdown
  /**
     * Initiates an orderly shutdown in which previously submitted
     * tasks are executed, but no new tasks will be accepted.
     * Invocation has no additional effect if already shut down.
     *
     * <p>This method does not wait for previously submitted tasks to
     * complete execution.  Use {@link #awaitTermination awaitTermination}
     * to do that.
     **/

停止接收新任务,原来的任务继续执行 ,不会阻塞主线程。
如果需要等待完成则需使用awaitTermination方法。

例2

public class ExceptionDemo {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(1);

        try {
            Future<Double> future = executorService.submit(() -> {
                int a = 1;
                return 10.0/(a-1);
            });

            double b = future.get();
            System.out.println(b);

        } catch (Exception ex) {
            System.out.println("catch execute");
            ex.printStackTrace();
        }

        try {
            executorService.execute(() -> {
                    int a = 1;
                    float b = 10/(a-1);
                });
        } catch (Exception ex) {
            System.out.println("catch execute");
            ex.printStackTrace();
        }

        executorService.shutdown();
        System.out.println("Main Thread End!");
    }

1.3 ThreadFactory

image.png
创建新线程

1.4 ThreadPoolExecutor 提交任务逻辑

image.png

  1. 判断 corePoolSize 【创建】
  2. 加入 workQueue
  3. 判断 maximumPoolSize 【创建】
  4. 执行拒绝策略处理器

1.5 线程池参数

(1)缓冲队列
BlockingQueue 是双缓冲队列。BlockingQueue 内部使用两条队列,允许两个线程同时向队列一个存储,一个取出操作。在保证并发安全的同时,提高了队列的存取效率。

  1. ArrayBlockingQueue:规定大小的 BlockingQueue,其构造必须指定大小。其所含的对象是 FIFO 顺序排序的。
  2. LinkedBlockingQueue:大小不固定的 BlockingQueue,若其构造时指定大小,生成的 BlockingQueue 有大小限制,不指定大小,其大小有Integer.MAX_VALUE 来决定。其所含的对象是 FIFO 顺序排序的。
  3. PriorityBlockingQueue:类似于 LinkedBlockingQueue,但是其所含对象的排序不是 FIFO,而是依据对象的自然顺序或者构造函数的 Comparator 决定。
  4. SynchronizedQueue:特殊的 BlockingQueue,对其的操作必须是放和取交替完成。

(2)拒绝策略

  1. ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出 RejectedExecutionException
    异常。
  2. ThreadPoolExecutor.DiscardPolicy:丢弃任务,但是不抛出异常。
  3. ThreadPoolExecutor.DiscardOldestPolicy:丢弃队列最前面的任务,然后重新提
    交被拒绝的任务
  4. ThreadPoolExecutor.CallerRunsPolicy:由调用线程(提交任务的线程)处理该任
    务

第四种用的比较多。

1.6 ThreadFactory 示例

public class CustomThreadFactory implements ThreadFactory {
    private AtomicInteger serial = new AtomicInteger(0);

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r);
        thread.setDaemon(true); // 根据需要,设置守护线程
        thread.setName("CustomThread-" + serial.getAndIncrement());
        return thread;
    }
}

可以根据业务设置线程的名称,方便在排查问题。

1.7 ThreadPoolExecutor 示例

image.png

image.png

public static ThreadPoolExecutor initThreadPoolExecutor() {
int coreSize = Runtime.getRuntime().availableProcessors();
int maxSize = Runtime.getRuntime().availableProcessors() * 2;
BlockingQueue<Runnable> workQueue = new 
LinkedBlockingDeque<>(500);
CustomThreadFactory threadFactory = new CustomThreadFactory();
ThreadPoolExecutor executor = new ThreadPoolExecutor(coreSize, 
maxSize,
1, TimeUnit.MINUTES, workQueue, threadFactory);
return executor;
}
  1. newSingleThreadExecutor
    创建一个单线程的线程池。这个线程池只有一个线程在工作,也就是相当于单线程串行执行所有任务。如果这个唯一的线程因为异常结束,那么会有一个新的线程来替代它。此线程池保证所有任务的执行顺序按照任务的提交顺序执行。
    2.newFixedThreadPool
    创建固定大小的线程池。每次提交一个任务就创建一个线程,直到线程达到线程池的最大大小。线程池的大小一旦达到最大值就会保持不变,如果某个线程因为执行异常而结束,那么线程池会补充一个新线程。
  2. newCachedThreadPool
    创建一个可缓存的线程池。如果线程池的大小超过了处理任务所需要的线程,那么就会回收部分空闲(60秒不执行任务)的线程,当任务数增加时,此线程池又可以智能的添加新线程来处理任务。此线程池不会对线程池大小做限制,线程池大小完全依赖于操作系统(或者
    说JVM)能够创建的最大线程大小。
    4.newScheduledThreadPool
    创建一个大小无限的线程池。此线程池支持定时以及周期性执行任务的需求。

创建固定线程池的经验
不是越大越好,太小肯定也不好:
假设核心数为N,
1、如果是CPU密集型应用,则线程池大小设置为N或N+1
2、如果是IO密集型应用,则线程池大小设置为2N或2N+2

1.8 Callable ,Future– 基础接口

Runnable Callable 对比
对比:
•
Runnable#run()没有返回值
•
Callable#call()方法有返回值
Future:
image.png

public class RandomSleepTask implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        Integer sleep = new Random().nextInt(10000);
        TimeUnit.MILLISECONDS.sleep(sleep);
        return sleep;
    }
}

public class FutureTest {
    public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
        RandomSleepTask randomSleepTask = new RandomSleepTask();
        ExecutorService executorService = initThreadPoolExecutor();
        Future<Integer> future1 = executorService.submit(randomSleepTask);
        Future<Integer> future2 = executorService.submit(randomSleepTask);

        Integer result1 = future1.get(3, TimeUnit.SECONDS);
        Integer result2 = future2.get(3, TimeUnit.SECONDS);

        System.out.println("result1=" + result1);
        System.out.println("result2=" + result2);

    }


    public static ThreadPoolExecutor initThreadPoolExecutor() {

        int coreSize = Runtime.getRuntime().availableProcessors();
        int maxSize = Runtime.getRuntime().availableProcessors() * 2;
        BlockingQueue<Runnable> workQueue = new
                LinkedBlockingDeque<>(500);
        CustomThreadFactory threadFactory = new CustomThreadFactory();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(coreSize,
                maxSize,
                1, TimeUnit.MINUTES, workQueue, threadFactory);
        return executor;
    }
}
public class ThreadPoolTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 60,
                TimeUnit.SECONDS, new ArrayBlockingQueue<>(10), new CustomThreadFactory(), new ThreadPoolExecutor.AbortPolicy());

        for (int i = 0; i < 200; i++) {
            final int a = i;

      /*      Future<?> submit = threadPoolExecutor.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("1111121");
                }
            });
            Object o = submit.get();
            System.out.println(o);
*/
            Future<Integer> submit1 = threadPoolExecutor.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    int s = a;
                    return s;
                }
            });

            Integer integer = submit1.get();
            System.out.println("ins:" + integer);
        }

  }
}


public class CustomThreadFactory implements ThreadFactory {
    private AtomicInteger serial = new AtomicInteger(0);

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r);
        thread.setDaemon(true); // 根据需要,设置守护线程
        thread.setName("CustomThread-" + serial.getAndIncrement());
        return thread;
    }
}

2 java并发包

2.1 java包介绍

2.1.1 JDK 核心库的包

image.png

2.1.2 java.util.concurrent

image.png

锁机制类 Locks : Lock, Condition, ReentrantLock, ReadWriteLock,LockSupport
原子操作类 Atomic : AtomicInteger, AtomicLong, LongAdder
线程池相关类 Executer : Future, Callable, Executor, ExecutorService
信号量三组工具类 Tools : CountDownLatch, CyclicBarrier, Semaphore
并发集合类 Collections : CopyOnWriteArrayList, ConcurrentMap

2.2 java的锁介绍

2.2.1 synchronized方式的问题:

1、同步块的阻塞无法中断(不能Interruptibly)
2、同步块的阻塞无法控制超时(无法自动解锁)
3、同步块无法异步处理锁(即不能立即知道是否可以拿到锁)
4、同步块无法根据条件灵活的加锁解锁(即只能跟同步块范围一致)

2.2.2 Lock

lock基于AQS的
image.png

image.png

例子:

public class LockCounter {

    private int sum = 0; // 可重入锁+公平锁
    private Lock lock = new ReentrantLock(true);

    public int addAndGet() {
     /*   synchronized(this) {
            return ++sum;
        }*/
        lock.lock();
        try {
            return ++sum;
        } finally {
            lock.unlock();
        }
    }

    public int getSum() {
        return sum;
    }
}



public class TestLockCounter {
    public static void main(String[] args) {
        int loopNum = 100_0000;
        LockCounter counter = new LockCounter();
        IntStream.range(0, loopNum).parallel().forEach(i -> counter.addAndGet());
        System.out.println(counter.getSum());


    }
}

什么是可重入锁?
说某个线程已经获得某个锁,可以再次获取锁而不会出现死锁
— 第二次进入时是否阻塞。
什么是公平锁?
— 公平锁意味着排队靠前的优先。
— 非公平锁则是都是同样机会。

2.2.3 读写锁

image.png

2.2.4 Condition

image.png

2.2.4 LockSupport—锁当前线程

image.png

2.2.5 用锁的最佳实践

Doug Lea《Java 并发编程:设计原则与模式》一书中, 推荐的三个用锁的最佳实践,它们分别是:
1. 永远只在更新对象的成员变量时加锁
2. 永远只在访问可变的成员变量时加锁
3. 永远不在调用其他对象的方法时加锁
总结-最小使用锁: 1、降低锁范围:锁定代码的范围/作用域
2、细分锁粒度:讲一个大锁,拆分成多个小锁

相关问题:
Java1期第7课问题收集.pdf

2.3 并发原子类

2.3.1 Atomic 工具类

image.png
image.png
image.png

2.3.2 LongAdder 对 AtomicLong 的改进

**

image.png

2.4 并发工具类

2.4.1 什么是并发工具类

image.png

2.4.2 AQS

image.png

基于aqs的相关工具类

2.4.2.1 Semaphore - 信号量

image.png

2.4.2.2 CountdownLatch

image.png
image.png

2.4.2.3 CyclicBarrier

image.png
image.png

2.4.2.4 CountDownLatch与CyclicBarrier比较

image.png
image.png

2.4.3 Future/FutureTask/CompletableFuture

image.png

image.png
image.png