美文网首页
2022-07-26_Jdk调度线程服务ScheduledThr

2022-07-26_Jdk调度线程服务ScheduledThr

作者: kikop | 来源:发表于2022-07-27 08:14 被阅读0次

20220726_Jdk调度线程服务ScheduledThreadPoolExecutor学习笔记.md

1概述

1.1ScheduledThreadPoolExecutor类图结构

image-20220726075028108.png

从类图结构我们看出,ScheduledThreadPoolExecutor继承了ThreadPoolExecutor并实现了ScheduledExecutorService接口。

ThreadPoolExecutor具备线程池的创建管理功能。

提交给队列的任务本质都实现了Runnable接口。每个线程都被封装成Worker,通过getTask进行任务的获取、通过委托runWorker进行任务运行。

ScheduledExecutorService定义了周期性或一次性任务的执行接口。

1.2ThreadPoolExecutor基类

定义了模板方法,getTask()。

// C:\Program Files\Java\jdk1.8.0_60\src.zip!\java\util\concurrent\ThreadPoolExecutor.java
// 定义线程池可重入锁
// 线程的并发管理(创建、中断、销毁等)
private final ReentrantLock mainLock = new ReentrantLock();

1.3ScheduledThreadPoolExecutor子类

// 构造ScheduledThreadPoolExecutor
public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue());
    }
public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize, // max
                              long keepAliveTime, // 0
                              TimeUnit unit, // ns
                              BlockingQueue<Runnable> workQueue) { // 阻塞队列
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    
    
    }

1.3.1ScheduledFutureTask

封装的某个任务并提交到线程池。

private class Scheduled FutureTask<V>
    extends FutureTask<V> implements RunnableScheduledFuture<V> {
    
public interface Runnable Scheduled Future<V> extends RunnableFuture<V>, ScheduledFuture<V> {

public interface ScheduledFuture<V> extends Delayed, Future<V> { // 从这里我们可以看出,Scheduled本质继承了Delayed接口
    
public interface Runnable uture<V> extends Runnable, Future<V> {

1.3.2DelayedWorkQueue

延迟队列,实现小顶堆,本质也是BlockingQueue,作为线程池的workQueue。用于从队列DelayedWorkQueeu中取任务ScheduledFutureTask。

static class DelayedWorkQueue extends AbstractQueue<Runnable>
        implements BlockingQueue<Runnable> {
    // 这里队列的本质为数组,RunnableScheduledFuture<?>[]extends Delayed
    private RunnableScheduledFuture<?>[] queue =
            new RunnableScheduledFuture<?>[INITIAL_CAPACITY];
    
    // 获取队列中的任务
    // 因为DelayedWorkQueue是线程池共用的,所以加锁,确保并发安全
    private final ReentrantLock lock = new ReentrantLock();
    // peek
    public RunnableScheduledFuture<?> peek() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return queue[0];
        } finally {
            lock.unlock();
        }
    }

1.3.2.1任务添加offer(put、add)

public void put(Runnable e) {
    offer(e);
}

public boolean add(Runnable e) {
    return offer(e);
}

public boolean offer(Runnable e, long timeout, TimeUnit unit) {
    return offer(e);
}
public boolean offer(Runnable x) {
            if (x == null)
                throw new NullPointerException();
            RunnableScheduledFuture<?> e = (RunnableScheduledFuture<?>)x;
            final ReentrantLock lock = this.lock;
            lock.lock();
            try {
                int i = size;
                if (i >= queue.length)
                    grow();
                size = i + 1;
                if (i == 0) {
                    queue[0] = e;
                    setIndex(e, 0);
                } else {
                    siftUp(i, e);
                }
                if (queue[0] == e) {
                    leader = null;
                    available.signal();
                }
            } finally {
                lock.unlock();
            }
            return true;
        }

1.3.2.2任务获取takde vs poll

// 无限等待信号到来
public RunnableScheduledFuture<?> take() throws InterruptedException {
            final ReentrantLock lock = this.lock;
            lock.lockInterruptibly(); // 可中断的锁
            try {
                for (;;) { // 无限循环
                    RunnableScheduledFuture<?> first = queue[0];
                    if (first == null)
                        available.await(); // 没有则等待信号
                    else {
                        long delay = first.getDelay(NANOSECONDS);
                        if (delay <= 0)
                            return finishPoll(first);
                        first = null; // don't retain ref while waiting
                        if (leader != null)
                            available.await(); // 没有则等待信号
                        else {
                            Thread thisThread = Thread.currentThread();
                            leader = thisThread; // 记录当前线程
                            try {
                                available.awaitNanos(delay); // 等待指定的时间
                            } finally {
                                if (leader == thisThread)
                                    leader = null;
                            }
                        }
                    }
                }
            } finally {
                if (leader == null && queue[0] != null)
                    available.signal();
                lock.unlock();
            }
        }
// 不等待,没有则直接返回
public RunnableScheduledFuture<?> poll() {
            final ReentrantLock lock = this.lock;
            lock.lock();
            try {
                RunnableScheduledFuture<?> first = queue[0];
                if (first == null || first.getDelay(NANOSECONDS) > 0)
                    return null;
                else
                    return finishPoll(first);
            } finally {
                lock.unlock();
            }
        }
// 等待,指定时间 by awaitNanos
public RunnableScheduledFuture<?> poll(long timeout, TimeUnit unit)
            throws InterruptedException {
            long nanos = unit.toNanos(timeout);
            final ReentrantLock lock = this.lock;
            lock.lockInterruptibly();
            try {
                for (;;) {
                    RunnableScheduledFuture<?> first = queue[0];
                    if (first == null) {
                        if (nanos <= 0)
                            return null;
                        else
                            nanos = available.awaitNanos(nanos);
                    } else {
                        long delay = first.getDelay(NANOSECONDS);
                        if (delay <= 0)
                            return finishPoll(first);
                        if (nanos <= 0)
                            return null;
                        first = null; // don't retain ref while waiting
                        if (nanos < delay || leader != null)
                            nanos = available.awaitNanos(nanos);
                        else {
                            Thread thisThread = Thread.currentThread();
                            leader = thisThread;
                            try {
                                long timeLeft = available.awaitNanos(delay);
                                nanos -= delay - timeLeft;
                            } finally {
                                if (leader == thisThread)
                                    leader = null;
                            }
                        }
                    }
                }
            } finally {
                if (leader == null && queue[0] != null)
                    available.signal();
                lock.unlock();
            }
        }

1.4外部任务管理

1.4.1任务添加ScheduledThreadPoolExecutor#delayedExecute

将延时任务添加到DelayedWorkQueue中。

public ScheduledFuture<?> schedule(Runnable command,
                                       long delay,
                                       TimeUnit unit) {
        if (command == null || unit == null)
            throw new NullPointerException();
    // 这里,decorateTask啥也没做
        RunnableScheduledFuture<?> t = decorateTask(command,
            new ScheduledFutureTask<Void>(command, null,
                                          triggerTime(delay, unit)));
        delayedExecute(t);
        return t;
    }
    private void delayedExecute(RunnableScheduledFuture<?> task) {
        if (isShutdown())
            reject(task);
        else {
            super.getQueue().add(task);

1.4.2任务获取ThreadPoolExecutor#getTask

重点:getTask是一个模板方法。

C:\Program Files\Java\jdk1.8.0_60\src.zip!\java\util\concurrent\ThreadPoolExecutor.java
private Runnable getTask() {
                try {
                Runnable r = timed ?
                    workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                    workQueue.take();

1.4.2.1DelayedWorkQueue#Take(具体参看1.3.2.2)


1.4.2.2DelayedWorkQueue#Pool(具体参看1.3.2.2)


1.5任务执行(具体的业务逻辑)

2代码示例

参考

相关文章

  • 2022-07-26_Jdk调度线程服务ScheduledThr

    20220726_Jdk调度线程服务ScheduledThreadPoolExecutor学习笔记.md 1概述 ...

  • ThreadScheduledPool

    ScheduledThreadPoolExecutor是一个使用线程池执行定时任务的类。 ScheduledThr...

  • java虚拟机读书笔记之线程调度

    java线程调度 线程调度主要有两种方式,协同式线程调度和抢占式线程调度。1、协同式: 线程的执行时间由线程本身...

  • [Java]线程和锁

    0x00 线程调度 线程调度指的是系统为线程分配CPU使用权。分为两种: 协同式线程调度线程想用CPU多久就用多久...

  • CPU调度

    CPU调度 基本概念 CPU调度在讨论普通调度概念时使用进程调度,特别指定为线程概念时使用线程调度 CPU-I/O...

  • 2018-04-03 线程基础

    线程调度 是指系统分配CPU使用权限的方式,分为协同式线程调度和抢占式线程调度 进程、线程概念 进程是应用程序的一...

  • 什么是线程调度器(Thread Scheduler)和时间分片(

    线程调度器是一个操作系统服务,它负责为 Runnable 状态的线程分配 CPU 时间。一旦我们创建一个线程并启动...

  • 线程优先级和守护线程

    线程优先级: Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定调度哪个...

  • 并发--线程和锁

    线程调度 协同式调度 1.一个线程执行完毕之后再通知其他线程执行 抢占式调度(JAVA使用的是这种方式) 1.os...

  • 2.1 Java线程调度

    线程调度是指系统为线程分配处理器使用权的过程,主要调度方式有两种,分别是协同式线程调度(CooperativeTh...

网友评论

      本文标题:2022-07-26_Jdk调度线程服务ScheduledThr

      本文链接:https://www.haomeiwen.com/subject/eenairtx.html