Concurrent Program-05:不可变类_线程池(ThreadPoolExcutor & Fork/Join)

1. 不可变类

如果一个对象不能够修改其内部状态(属性),那么它就是线程安全的,因为不存在并发修改啊!这样的对象在Java 中有很多,例如在 Java 8 后,提供了一个新的日期格式化类:
在这里插入图片描述
另一个大家更为熟悉的 String 类也是不可变的,以它为例,说明一下不可变设计的要素
在这里插入图片描述
发现该类、类中所有属性都是 final 的:

  • 属性用 final 修饰保证了该属性是只读的,不能修改
  • 类用 final 修饰保证了该类中的方法不能被覆盖,防止子类无意间破坏不可变性

2. 线程池(重要)

在这里插入图片描述

1. 自定义线程池

1、拒绝策略:

@FunctionalInterface // 拒绝策略
interface RejectPolicy<T> {
    void reject(BlockingQueue<T> queue, T task);
}

2、定义阻塞队列:

@Slf4j(topic = "c.BlockingQueue")
class BlockingQueue<T> {
    // 1. 任务队列
    private Deque<T> queue = new ArrayDeque<>();

    // 2. 锁
    private ReentrantLock lock = new ReentrantLock();

    // 3. 生产者条件变量
    private Condition fullWaitSet = lock.newCondition();

    // 4. 消费者条件变量
    private Condition emptyWaitSet = lock.newCondition();

    // 5. 容量
    private int capcity;

    //创建队列就有容量
    public BlockingQueue(int capcity) {
        this.capcity = capcity;
    }

    // 带超时阻塞获取 ,保证不需要永久等待
    public T poll(long timeout, TimeUnit unit) {
        //加锁
        lock.lock();
        try {
            // 将timeout统一转换为纳秒
            long nanos = unit.toNanos(timeout);

            //队列为空等待
            while (queue.isEmpty()) {
                try {
                    // 返回值是剩余时间
                    if (nanos <= 0) {
                        return null;
                    }
                    nanos = emptyWaitSet.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T t = queue.removeFirst();
            fullWaitSet.signal();
            return t;
        } finally {
            //释放锁
            lock.unlock();
        }
    }

    // 阻塞获取
    public T take() {
        //加锁
        lock.lock();
        try {
            //队列为空时等待
            while (queue.isEmpty()) {
                try {
                    emptyWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T t = queue.removeFirst();
            fullWaitSet.signal();
            return t;
        } finally {
            lock.unlock();
        }
    }

    // 阻塞添加
    public void put(T task) {
        //加锁
        lock.lock();
        try {
            //队列满时,等待
            while (queue.size() == capcity) {
                try {
                    log.debug("等待加入任务队列 {} ...", task);
                    fullWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            log.debug("加入任务队列 {}", task);
            queue.addLast(task);
            emptyWaitSet.signal();
        } finally {
            lock.unlock();
        }
    }

    // 带超时时间阻塞添加,保证无需永久等待
    public boolean offer(T task, long timeout, TimeUnit timeUnit) {
        //加锁
        lock.lock();
        try {
            //将其他时间单位转换为ns
            long nanos = timeUnit.toNanos(timeout);
            //队列尾满时等待
            while (queue.size() == capcity) {
                try {
                    
                    if(nanos <= 0) {
                        return false;
                    }
                    log.debug("等待加入任务队列 {} ...", task);
                    
                    //返回的是剩余时间
                    nanos = fullWaitSet.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            log.debug("加入任务队列 {}", task);
            queue.addLast(task);
            emptyWaitSet.signal();
            return true;
        } finally {
            lock.unlock();
        }
    }

    public int size() {
        lock.lock();
        try {
            return queue.size();
        } finally {
            lock.unlock();
        }
    }

    public void tryPut(RejectPolicy<T> rejectPolicy, T task) {
        lock.lock();
        try {
            // 判断队列是否满
            if(queue.size() == capcity) {
                rejectPolicy.reject(this, task);
            } else {  // 有空闲
                log.debug("加入任务队列 {}", task);
                queue.addLast(task);
                emptyWaitSet.signal();
            }
        } finally {
            lock.unlock();
        }
    }
}

3、自定义线程池:

@Slf4j(topic = "c.ThreadPool")
class ThreadPool {
    // 任务队列
    private BlockingQueue<Runnable> taskQueue;

    // 线程集合
    private HashSet<Worker> workers = new HashSet<>();

    // 核心线程数
    private int coreSize;

    // 获取任务时的超时时间
    private long timeout;

    //指定时间单位
    private TimeUnit timeUnit;

    //拒绝策略
    private RejectPolicy<Runnable> rejectPolicy;

    public ThreadPool(int coreSize, long timeout, TimeUnit timeUnit, int queueCapcity, RejectPolicy<Runnable> rejectPolicy) {
        this.coreSize = coreSize;
        this.timeout = timeout;
        this.timeUnit = timeUnit;
        this.taskQueue = new BlockingQueue<>(queueCapcity);
        this.rejectPolicy = rejectPolicy;
    }

    // 执行任务
    public void execute(Runnable task) {
        // 当任务数没有超过 coreSize 时,直接交给 worker 对象执行
        // 如果任务数超过 coreSize 时,加入任务队列暂存
        synchronized (workers) {
            if(workers.size() < coreSize) {
                Worker worker = new Worker(task);
                log.debug("新增 worker{}, {}", worker, task);
                workers.add(worker);
                worker.start();
            } else {
//                taskQueue.put(task);
                // 1) 死等
                // 2) 带超时等待
                // 3) 让调用者放弃任务执行
                // 4) 让调用者抛出异常
                // 5) 让调用者自己执行任务
                taskQueue.tryPut(rejectPolicy, task);
            }
        }
    }



    class Worker extends Thread{
        private Runnable task;

        public Worker(Runnable task) {
            this.task = task;
        }

        @Override
        public void run() {
            // 执行任务
            // 1) 当 task 不为空,执行任务
            // 2) 当 task 执行完毕,再接着从任务队列获取任务并执行
//            while(task != null || (task = taskQueue.take()) != null) {
            while(task != null || (task = taskQueue.poll(timeout, timeUnit)) != null) {
                try {
                    log.debug("正在执行...{}", task);
                    task.run();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    task = null;
                }
            }
            synchronized (workers) {
                log.debug("worker 被移除{}", this);
                workers.remove(this);
            }
        }
    }
}

4、测试:

@Slf4j(topic = "c.TestPool")
public class TestPool {
    public static void main(String[] args) {
        ThreadPool threadPool = new ThreadPool(2,
                1000, TimeUnit.MILLISECONDS, 10, (queue, task)->{
            // 1. 死等
//            queue.put(task);
            // 2) 带超时等待
//            queue.offer(task, 1500, TimeUnit.MILLISECONDS);
            // 3) 让调用者放弃任务执行
//            log.debug("放弃{}", task);
            // 4) 让调用者抛出异常,剩余的任务不再执行
//            throw new RuntimeException("任务执行失败 " + task);
            // 5) 让调用者自己执行任务
            task.run();
        });
        for (int i = 0; i < 4; i++) {
            int j = i;
            threadPool.execute(() -> {
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.debug("{}", j);
            });
        }
    }
}

不带超时时间阻塞的结果:
在这里插入图片描述

17:39:15.854 c.ThreadPool [main] - 新增 workerThread[Thread-0,5,main], cn.itcast.n8.TestPool$$Lambda$2/1207140081@7e0babb1
17:39:15.866 c.ThreadPool [main] - 新增 workerThread[Thread-1,5,main], cn.itcast.n8.TestPool$$Lambda$2/1207140081@3cb5cdba
17:39:15.866 c.ThreadPool [Thread-0] - 正在执行...cn.itcast.n8.TestPool$$Lambda$2/1207140081@7e0babb1
17:39:15.867 c.BlockingQueue [main] - 加入任务队列 cn.itcast.n8.TestPool$$Lambda$2/1207140081@1134affc
17:39:15.867 c.ThreadPool [Thread-1] - 正在执行...cn.itcast.n8.TestPool$$Lambda$2/1207140081@3cb5cdba
17:39:15.867 c.BlockingQueue [main] - 加入任务队列 cn.itcast.n8.TestPool$$Lambda$2/1207140081@d041cf
17:39:16.867 c.TestPool [Thread-0] - 0
17:39:16.867 c.ThreadPool [Thread-0] - 正在执行...cn.itcast.n8.TestPool$$Lambda$2/1207140081@1134affc
17:39:16.870 c.TestPool [Thread-1] - 1
17:39:16.870 c.ThreadPool [Thread-1] - 正在执行...cn.itcast.n8.TestPool$$Lambda$2/1207140081@d041cf
17:39:17.867 c.TestPool [Thread-0] - 2
17:39:17.870 c.TestPool [Thread-1] - 3

带超时阻塞的结果:
在这里插入图片描述

17:42:18.392 c.ThreadPool [main] - 新增 workerThread[Thread-0,5,main], cn.itcast.n8.TestPool$$Lambda$2/1207140081@7e0babb1
17:42:18.401 c.ThreadPool [main] - 新增 workerThread[Thread-1,5,main], cn.itcast.n8.TestPool$$Lambda$2/1207140081@3cb5cdba
17:42:18.401 c.ThreadPool [Thread-0] - 正在执行...cn.itcast.n8.TestPool$$Lambda$2/1207140081@7e0babb1
17:42:18.401 c.BlockingQueue [main] - 加入任务队列 cn.itcast.n8.TestPool$$Lambda$2/1207140081@1134affc
17:42:18.401 c.ThreadPool [Thread-1] - 正在执行...cn.itcast.n8.TestPool$$Lambda$2/1207140081@3cb5cdba
17:42:18.402 c.BlockingQueue [main] - 加入任务队列 cn.itcast.n8.TestPool$$Lambda$2/1207140081@d041cf
17:42:19.401 c.TestPool [Thread-0] - 0
17:42:19.401 c.ThreadPool [Thread-0] - 正在执行...cn.itcast.n8.TestPool$$Lambda$2/1207140081@1134affc
17:42:19.402 c.TestPool [Thread-1] - 1
17:42:19.402 c.ThreadPool [Thread-1] - 正在执行...cn.itcast.n8.TestPool$$Lambda$2/1207140081@d041cf
17:42:20.401 c.TestPool [Thread-0] - 2
17:42:20.402 c.TestPool [Thread-1] - 3
17:42:21.402 c.ThreadPool [Thread-0] - worker 被移除Thread[Thread-0,5,main]
17:42:21.404 c.ThreadPool [Thread-1] - worker 被移除Thread[Thread-1,5,main]

2. ThreadPoolExcutor线程池

在这里插入图片描述1、线程状态:
在这里插入图片描述2、构造方法:

  • corePoolSize 核心线程数目 (最多保留的线程数)
  • maximumPoolSize 最大线程数目
  • keepAliveTime 生存时间 - 针对救急线程
  • unit 时间单位 - 针对救急线程
  • workQueue 阻塞队列
  • threadFactory 线程工厂 - 可以为线程创建时起个好名字
  • handler 拒绝策略
    在这里插入图片描述

工作方式:

  • 线程池中刚开始没有线程,当一个任务提交给线程池后,线程池会创建一个新线程来执行任务。
  • 当线程数达到 corePoolSize 并没有线程空闲,这时再加入任务,新加的任务会被加入workQueue 队列排队,直到有空闲的线程。
  • 如果队列选择了有界队列,那么任务超过了队列大小时,会创建 maximumPoolSize - corePoolSize 数目的线程来救急。
  • 如果线程到达 maximumPoolSize 仍然有新任务这时会执行拒绝策略。拒绝策略 jdk 提供了 4 种实现。
    AbortPolicy :让调用者抛出 RejectedExecutionException 异常,这是默认策略
    CallerRunsPolicy: 让调用者运行任务
    DiscardPolicy :放弃本次任务
    DiscardOldestPolicy :放弃队列中最早的任务,本任务取而代之
    在这里插入图片描述
  • 当高峰过去后,超过corePoolSize 的救急线程如果一段时间没有任务做,需要结束节省资源,这个时间由keepAliveTime 和 unit 来控制。
    在这里插入图片描述

根据这个构造方法,JDK Executors 类提供了众多工厂方法来创建各种用途的线程池:

3、newFixedThreadPool:
在这里插入图片描述
特点:
 核心线程数 == 最大线程数(没有救急线程被创建),因此也无需超时时间
 阻塞队列是无界的,可以放任意数量的任务
核心线程即使队列中没有任务了,也不会停止运行。

4、newCachedThreadPool:
在这里插入图片描述

  • 核心线程数是 0, 最大线程数是 Integer.MAX_VALUE,救急线程的空闲生存时间是 60s,意味着全部都是救急线程(60s 后可以回收)救急线程可以无限创建
  • 队列采用了 SynchronousQueue 实现特点是,它没有容量,没有线程来取是放不进去的(一手交钱、一手交货)
@Slf4j(topic = "c.TestSynchronousQueue")
public class TestSynchronousQueue {
    public static void main(String[] args) {
        SynchronousQueue<Integer> integers = new SynchronousQueue<>();
        new Thread(() -> {
            try {
                log.debug("putting {} ", 1);
                integers.put(1);
                log.debug("{} putted...", 1);

                log.debug("putting...{} ", 2);
                integers.put(2);
                log.debug("{} putted...", 2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"t1").start();

        sleep(1);

        new Thread(() -> {
            try {
                log.debug("taking {}", 1);
                integers.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"t2").start();

        sleep(1);

        new Thread(() -> {
            try {
                log.debug("taking {}", 2);
                integers.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"t3").start();
    }
}

结果:在take之前,put是阻塞的:

20:39:03.553 c.TestSynchronousQueue [t1] - putting 1 
20:39:04.557 c.TestSynchronousQueue [t2] - taking 1
20:39:04.558 c.TestSynchronousQueue [t1] - 1 putted...
20:39:04.558 c.TestSynchronousQueue [t1] - putting...2 
20:39:05.552 c.TestSynchronousQueue [t3] - taking 2
20:39:05.552 c.TestSynchronousQueue [t1] - 2 putted...

整个线程池表现为线程数会根据任务量不断增长,没有上限,当任务执行完毕,空闲 1分钟后释放线程。 适合任务数比较密集,但每个任务执行时间较短的情况

5、 newSingleThreadExecutor:
在这里插入图片描述
使用场景:
希望多个任务排队执行。线程数固定为 1,任务数多于 1 时,会放入无界队列排队。任务执行完毕,这唯一的线程也不会被释放。

(1) 自己创建的单个线程和从线程池中只有一个线程有什么区别?

  • 自己创建一个单线程串行执行任务,如果任务执行失败而终止那么没有任何补救措施,而线程池还会新建一个线程,保证池的正常工作

(2) Executors.newSingleThreadExecutor()Executors.newFixedThreadPool(1)的区别?

  • Executors.newSingleThreadExecutor() 线程个数始终为1,不能修改
    FinalizableDelegatedExecutorService 应用的是装饰器模式,只对外暴露了ExecutorService 接口,因此不能调用 ThreadPoolExecutor 中特有的方法
  • Executors.newFixedThreadPool(1) 初始时为1,以后还可以修改
    对外暴露的是 ThreadPoolExecutor 对象,可以强转后调用 setCorePoolSize 等方法进行修改。

6、 提交任务:

使用Future + Callable提交任务
在这里插入图片描述

@Slf4j(topic = "c.TestSubmit")
public class TestSubmit {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //创建一个核心线程为3的线程池
        ExecutorService pool = Executors.newFixedThreadPool(3);
        method3(pool);
    }

    private static void method3(ExecutorService pool) throws InterruptedException, ExecutionException {

        //提交tasks中所有任务,哪个任务先成功执行完毕,返回此任务执行结果,其它任务取消
        String result = pool.invokeAny(Arrays.asList(
                () -> {
                    log.debug("begin 1");
                    Thread.sleep(1000);
                    log.debug("end 1");
                    return "1";
                },
                () -> {
                    log.debug("begin 2");
                    Thread.sleep(500);
                    log.debug("end 2");
                    return "2";
                },
                () -> {
                    log.debug("begin 3");
                    Thread.sleep(2000);
                    log.debug("end 3");
                    return "3";
                }
        ));
        log.debug("{}", result);
    }

    private static void method2(ExecutorService pool) throws InterruptedException {
        //提交tasks中所有任务,用futures接收执行结果
        List<Future<String>> futures = pool.invokeAll(Arrays.asList(
                () -> {
                    log.debug("begin");
                    Thread.sleep(1000);
                    return "1";
                },
                () -> {
                    log.debug("begin");
                    Thread.sleep(500);
                    return "2";
                },
                () -> {
                    log.debug("begin");
                    Thread.sleep(2000);
                    return "3";
                }
        ));

        //遍历结果
        futures.forEach( f ->  {
            try {
                log.debug("{}", f.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        });
    }

    private static void method1(ExecutorService pool) throws InterruptedException, ExecutionException {

        //提交任务 task,用返回值 Future 获得任务执行结果
        Future<String> future = pool.submit(() -> {
            log.debug("running");
            Thread.sleep(1000);
            return "ok";
        });
        log.debug("{}", future.get());
    }
}

7、关闭线程池:
在这里插入图片描述
在这里插入图片描述在这里插入图片描述

@Slf4j(topic = "c.TestShutDown")
public class TestShutDown {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(2);

        Future<Integer> result1 = pool.submit(() -> {
            log.debug("task 1 running...");
            Thread.sleep(1000);
            log.debug("task 1 finish...");
            return 1;
        });

        Future<Integer> result2 = pool.submit(() -> {
            log.debug("task 2 running...");
            Thread.sleep(1000);
            log.debug("task 2 finish...");
            return 2;
        });

        Future<Integer> result3 = pool.submit(() -> {
            log.debug("task 3 running...");
            Thread.sleep(1000);
            log.debug("task 3 finish...");
            return 3;
        });

        log.debug("shutdown");
//        pool.shutdown();
//        pool.awaitTermination(3, TimeUnit.SECONDS);
        List<Runnable> runnables = pool.shutdownNow();
        log.debug("other.... {}" , runnables);
    }
}

8、任务调度线程池:

在『任务调度线程池』功能加入之前,可以使用 java.util.Timer 来实现定时功能,Timer 的优点在于简单易用,但由于所有任务都是由同一个线程来调度,因此所有任务都是串行执行的,同一时间只能有一个任务在执行,前一个任务的延迟或异常都将会影响到之后的任务。

@Slf4j(topic = "c.TestTimer")
public class TestTimer {
    public static void main(String[] args){
        method1();
    }
    private static void method1() {
    	//创建一个定时器
        Timer timer = new Timer();
        //task1
        TimerTask task1 = new TimerTask() {
            @Override
            public void run() {
                log.debug("task 1");
                sleep(2);
            }
        };
        //task2
        TimerTask task2 = new TimerTask() {
            @Override
            public void run() {
                log.debug("task 2");
            }
        };

        log.debug("start...");
        //使用timer添加两个任务,希望它们都在 1s 后执行
        //但由于timer内只有一个线程来顺序执行队列中的任务,因此『任务1』的延时,影响了『任务2』的执行
        timer.schedule(task1, 1000);
        timer.schedule(task2, 1000);
    }
}

通过结果中时间可以看出,任务的延时时间变成3s才执行:

21:27:13.998 c.TestTimer [main] - start...
21:27:15.004 c.TestTimer [Timer-0] - task 1
21:27:17.005 c.TestTimer [Timer-0] - task 2

而且如果第一个任务发生异常,第二个任务就不再执行。

使用 ScheduledExecutorService 改写:

@Slf4j(topic = "c.TestTimer")
public class TestTimer {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);
        method2(pool);
    }
    private static void method2(ScheduledExecutorService pool) {
        pool.schedule(() -> {
            log.debug("task1");
            int i = 1 / 0;
        }, 1, TimeUnit.SECONDS);

        pool.schedule(() -> {
            log.debug("task2");
        }, 1, TimeUnit.SECONDS);
    }
}

输出结果:即使任务1出现异常,两个延时任务也能同时执行

21:35:15.894 c.TestTimer [pool-1-thread-1] - task2
21:35:15.894 c.TestTimer [pool-1-thread-2] - task1

使用 ScheduledExecutorService可以定时执行任务:

@Slf4j(topic = "c.TestTimer")
public class TestTimer {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        method3();
    }
    private static void method3() {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        log.debug("start...");
        //1:延时时间,1:时间间隔
        pool.scheduleAtFixedRate(() -> {
            log.debug("running...");
        }, 1, 1, TimeUnit.SECONDS);
    }
}

从结果可以看出:第一个任务延时1s执行,以后每隔1s执行1个任务

21:43:46.740 c.TestTimer [main] - start...
21:43:48.074 c.TestTimer [pool-1-thread-1] - running...
21:43:49.073 c.TestTimer [pool-1-thread-1] - running...
21:43:50.076 c.TestTimer [pool-1-thread-1] - running...
21:43:51.072 c.TestTimer [pool-1-thread-1] - running...

9、 正确处理执行任务异常:

方法1:主动捉异常

ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        pool.schedule(() -> {
            try {
                log.debug("task1");
                int i = 1 / 0;
            } catch (Exception e) {
                log.error("error:", e);
            }
        }, 1, TimeUnit.SECONDS);

方法2:使用 Future

 ExecutorService pool = Executors.newFixedThreadPool(1);
    pool.submit(() -> {
        try {
            log.debug("task1");
            int i = 1 / 0;
        } catch (Exception e) {
            log.error("error:", e);
        }
    });

3. Fork/Join线程池

在这里插入图片描述

发布了665 篇原创文章 · 获赞 115 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/qq_42764468/article/details/105012228