1. 程式人生 > >java.util.concurrent.ScheduledThreadPoolExecutor 原始碼

java.util.concurrent.ScheduledThreadPoolExecutor 原始碼

執行緒池相關

原始碼:

package java.util.concurrent;

import java.util.AbstractQueue;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import static java.util.concurrent.TimeUnit.NANOSECONDS;

public class ScheduledThreadPoolExecutor extends ThreadPoolExecutor implements ScheduledExecutorService {

    private volatile boolean continueExistingPeriodicTasksAfterShutdown;


    private volatile boolean executeExistingDelayedTasksAfterShutdown = true;


    private volatile boolean removeOnCancel = false;


    private static final AtomicLong sequencer = new AtomicLong();


    private class ScheduledFutureTask<V> extends FutureTask<V> implements RunnableScheduledFuture<V> {


        private final long sequenceNumber;


        private long time;


        private final long period;


        RunnableScheduledFuture<V> outerTask = this;


        int heapIndex;


        ScheduledFutureTask(Runnable r, V result, long ns) {
            super(r, result);
            this.time = ns;
            this.period = 0;
            this.sequenceNumber = sequencer.getAndIncrement();
        }


        ScheduledFutureTask(Runnable r, V result, long ns, long period) {
            super(r, result);
            this.time = ns;
            this.period = period;
            this.sequenceNumber = sequencer.getAndIncrement();
        }


        ScheduledFutureTask(Callable<V> callable, long ns) {
            super(callable);
            this.time = ns;
            this.period = 0;
            this.sequenceNumber = sequencer.getAndIncrement();
        }

        public long getDelay(TimeUnit unit) {
            return unit.convert(time - now(), NANOSECONDS);
        }

        public int compareTo(Delayed other) {
            if (other == this) // compare zero if same object
                return 0;
            if (other instanceof ScheduledFutureTask) {
                ScheduledFutureTask<?> x = (ScheduledFutureTask<?>) other;
                long diff = time - x.time;
                if (diff < 0)
                    return -1;
                else if (diff > 0)
                    return 1;
                else if (sequenceNumber < x.sequenceNumber)
                    return -1;
                else
                    return 1;
            }
            long diff = getDelay(NANOSECONDS) - other.getDelay(NANOSECONDS);
            return (diff < 0) ? -1 : (diff > 0) ? 1 : 0;
        }


        public boolean isPeriodic() {
            return period != 0;
        }


        private void setNextRunTime() {
            long p = period;
            if (p > 0)
                time += p;
            else
                time = triggerTime(-p);
        }

        public boolean cancel(boolean mayInterruptIfRunning) {
            boolean cancelled = super.cancel(mayInterruptIfRunning);
            if (cancelled && removeOnCancel && heapIndex >= 0)
                remove(this);
            return cancelled;
        }


        public void run() {
            boolean periodic = isPeriodic();
            if (!canRunInCurrentRunState(periodic))
                cancel(false);
            else if (!periodic)
                ScheduledFutureTask.super.run();
            else if (ScheduledFutureTask.super.runAndReset()) {
                setNextRunTime();
                reExecutePeriodic(outerTask);
            }
        }
    }

    static class DelayedWorkQueue extends AbstractQueue<Runnable>
            implements BlockingQueue<Runnable> {


        private static final int INITIAL_CAPACITY = 16;
        private RunnableScheduledFuture<?>[] queue =
                new RunnableScheduledFuture<?>[INITIAL_CAPACITY];
        private final ReentrantLock lock = new ReentrantLock();
        private int size = 0;


        private Thread leader = null;


        private final Condition available = lock.newCondition();


        private void setIndex(RunnableScheduledFuture<?> f, int idx) {
            if (f instanceof ScheduledFutureTask)
                ((ScheduledFutureTask) f).heapIndex = idx;
        }


        private void siftUp(int k, RunnableScheduledFuture<?> key) {
            while (k > 0) {
                int parent = (k - 1) >>> 1;
                RunnableScheduledFuture<?> e = queue[parent];
                if (key.compareTo(e) >= 0)
                    break;
                queue[k] = e;
                setIndex(e, k);
                k = parent;
            }
            queue[k] = key;
            setIndex(key, k);
        }


        private void siftDown(int k, RunnableScheduledFuture<?> key) {
            int half = size >>> 1;
            while (k < half) {
                int child = (k << 1) + 1;
                RunnableScheduledFuture<?> c = queue[child];
                int right = child + 1;
                if (right < size && c.compareTo(queue[right]) > 0)
                    c = queue[child = right];
                if (key.compareTo(c) <= 0)
                    break;
                queue[k] = c;
                setIndex(c, k);
                k = child;
            }
            queue[k] = key;
            setIndex(key, k);
        }


        private void grow() {
            int oldCapacity = queue.length;
            int newCapacity = oldCapacity + (oldCapacity >> 1); // grow 50%
            if (newCapacity < 0) // overflow
                newCapacity = Integer.MAX_VALUE;
            queue = Arrays.copyOf(queue, newCapacity);
        }


        private int indexOf(Object x) {
            if (x != null) {
                if (x instanceof ScheduledFutureTask) {
                    int i = ((ScheduledFutureTask) x).heapIndex;
                    // Sanity check; x could conceivably be a
                    // ScheduledFutureTask from some other pool.
                    if (i >= 0 && i < size && queue[i] == x)
                        return i;
                } else {
                    for (int i = 0; i < size; i++)
                        if (x.equals(queue[i]))
                            return i;
                }
            }
            return -1;
        }

        public boolean contains(Object x) {
            final ReentrantLock lock = this.lock;
            lock.lock();
            try {
                return indexOf(x) != -1;
            } finally {
                lock.unlock();
            }
        }

        public boolean remove(Object x) {
            final ReentrantLock lock = this.lock;
            lock.lock();
            try {
                int i = indexOf(x);
                if (i < 0)
                    return false;

                setIndex(queue[i], -1);
                int s = --size;
                RunnableScheduledFuture<?> replacement = queue[s];
                queue[s] = null;
                if (s != i) {
                    siftDown(i, replacement);
                    if (queue[i] == replacement)
                        siftUp(i, replacement);
                }
                return true;
            } finally {
                lock.unlock();
            }
        }

        public int size() {
            final ReentrantLock lock = this.lock;
            lock.lock();
            try {
                return size;
            } finally {
                lock.unlock();
            }
        }

        public boolean isEmpty() {
            return size() == 0;
        }

        public int remainingCapacity() {
            return Integer.MAX_VALUE;
        }

        public RunnableScheduledFuture<?> peek() {
            final ReentrantLock lock = this.lock;
            lock.lock();
            try {
                return queue[0];
            } finally {
                lock.unlock();
            }
        }

        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;
        }

        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);
        }


        private RunnableScheduledFuture<?> finishPoll(RunnableScheduledFuture<?> f) {
            int s = --size;
            RunnableScheduledFuture<?> x = queue[s];
            queue[s] = null;
            if (s != 0)
                siftDown(0, x);
            setIndex(f, -1);
            return f;
        }

        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();
            }
        }

        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(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();
            }
        }

        public void clear() {
            final ReentrantLock lock = this.lock;
            lock.lock();
            try {
                for (int i = 0; i < size; i++) {
                    RunnableScheduledFuture<?> t = queue[i];
                    if (t != null) {
                        queue[i] = null;
                        setIndex(t, -1);
                    }
                }
                size = 0;
            } finally {
                lock.unlock();
            }
        }


        private RunnableScheduledFuture<?> peekExpired() {
            // assert lock.isHeldByCurrentThread();
            RunnableScheduledFuture<?> first = queue[0];
            return (first == null || first.getDelay(NANOSECONDS) > 0) ?
                    null : first;
        }

        public int drainTo(Collection<? super Runnable> c) {
            if (c == null)
                throw new NullPointerException();
            if (c == this)
                throw new IllegalArgumentException();
            final ReentrantLock lock = this.lock;
            lock.lock();
            try {
                RunnableScheduledFuture<?> first;
                int n = 0;
                while ((first = peekExpired()) != null) {
                    c.add(first);   // In this order, in case add() throws.
                    finishPoll(first);
                    ++n;
                }
                return n;
            } finally {
                lock.unlock();
            }
        }

        public int drainTo(Collection<? super Runnable> c, int maxElements) {
            if (c == null)
                throw new NullPointerException();
            if (c == this)
                throw new IllegalArgumentException();
            if (maxElements <= 0)
                return 0;
            final ReentrantLock lock = this.lock;
            lock.lock();
            try {
                RunnableScheduledFuture<?> first;
                int n = 0;
                while (n < maxElements && (first = peekExpired()) != null) {
                    c.add(first);   // In this order, in case add() throws.
                    finishPoll(first);
                    ++n;
                }
                return n;
            } finally {
                lock.unlock();
            }
        }

        public Object[] toArray() {
            final ReentrantLock lock = this.lock;
            lock.lock();
            try {
                return Arrays.copyOf(queue, size, Object[].class);
            } finally {
                lock.unlock();
            }
        }

        @SuppressWarnings("unchecked")
        public <T> T[] toArray(T[] a) {
            final ReentrantLock lock = this.lock;
            lock.lock();
            try {
                if (a.length < size)
                    return (T[]) Arrays.copyOf(queue, size, a.getClass());
                System.arraycopy(queue, 0, a, 0, size);
                if (a.length > size)
                    a[size] = null;
                return a;
            } finally {
                lock.unlock();
            }
        }

        public Iterator<Runnable> iterator() {
            return new Itr(Arrays.copyOf(queue, size));
        }


        private class Itr implements Iterator<Runnable> {
            final RunnableScheduledFuture<?>[] array;
            int cursor = 0;     // index of next element to return
            int lastRet = -1;   // index of last element, or -1 if no such

            Itr(RunnableScheduledFuture<?>[] array) {
                this.array = array;
            }

            public boolean hasNext() {
                return cursor < array.length;
            }

            public Runnable next() {
                if (cursor >= array.length)
                    throw new NoSuchElementException();
                lastRet = cursor;
                return array[cursor++];
            }

            public void remove() {
                if (lastRet < 0)
                    throw new IllegalStateException();
                DelayedWorkQueue.this.remove(array[lastRet]);
                lastRet = -1;
            }
        }
    }


    public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
                new DelayedWorkQueue());
    }


    public ScheduledThreadPoolExecutor(int corePoolSize,
                                       ThreadFactory threadFactory) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
                new DelayedWorkQueue(), threadFactory);
    }


    public ScheduledThreadPoolExecutor(int corePoolSize,
                                       RejectedExecutionHandler handler) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
                new DelayedWorkQueue(), handler);
    }


    public ScheduledThreadPoolExecutor(int corePoolSize,
                                       ThreadFactory threadFactory,
                                       RejectedExecutionHandler handler) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
                new DelayedWorkQueue(), threadFactory, handler);
    }


    private long triggerTime(long delay, TimeUnit unit) {
        return triggerTime(unit.toNanos((delay < 0) ? 0 : delay));
    }


    long triggerTime(long delay) {
        return now() +
                ((delay < (Long.MAX_VALUE >> 1)) ? delay : overflowFree(delay));
    }


    private long overflowFree(long delay) {
        Delayed head = (Delayed) super.getQueue().peek();
        if (head != null) {
            long headDelay = head.getDelay(NANOSECONDS);
            if (headDelay < 0 && (delay - headDelay < 0))
                delay = Long.MAX_VALUE + headDelay;
        }
        return delay;
    }

    //建立並執行在給定延遲後啟用的一次性操作
    public ScheduledFuture<?> schedule(Runnable command,
                                       long delay,
                                       TimeUnit unit) {
        if (command == null || unit == null)
            throw new NullPointerException();
        RunnableScheduledFuture<?> t = decorateTask(command,
                new ScheduledFutureTask<Void>(command, null,
                        triggerTime(delay, unit)));
        delayedExecute(t);
        return t;
    }

    //建立並執行在給定延遲後啟用的 ScheduledFuture
    public <V> ScheduledFuture<V> schedule(Callable<V> callable,
                                           long delay,
                                           TimeUnit unit) {
        if (callable == null || unit == null)
            throw new NullPointerException();
        RunnableScheduledFuture<V> t = decorateTask(callable,
                new ScheduledFutureTask<V>(callable,
                        triggerTime(delay, unit)));
        delayedExecute(t);
        return t;
    }

    //建立並執行一個在給定初始延遲後首次啟用的定期操作,後續操作具有給定的週期;也就是將在initialDelay後開始執行,然後每隔period執行一次
    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                                  long initialDelay,
                                                  long period,
                                                  TimeUnit unit) {
        if (command == null || unit == null)
            throw new NullPointerException();
        if (period <= 0)
            throw new IllegalArgumentException();
        ScheduledFutureTask<Void> sft =
                new ScheduledFutureTask<Void>(command,
                        null,
                        triggerTime(initialDelay, unit),
                        unit.toNanos(period));
        RunnableScheduledFuture<Void> t = decorateTask(command, sft);
        sft.outerTask = t;
        delayedExecute(t);
        return t;
    }

    //建立並執行一個在給定初始延遲後首次啟用的定期操作,隨後,在每一次執行終止和下一次執行開始之間都存在給定的延遲
    public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                                     long initialDelay,
                                                     long delay,
                                                     TimeUnit unit) {
        if (command == null || unit == null)
            throw new NullPointerException();
        if (delay <= 0)
            throw new IllegalArgumentException();
        ScheduledFutureTask<Void> sft =
                new ScheduledFutureTask<Void>(command,
                        null,
                        triggerTime(initialDelay, unit),
                        unit.toNanos(-delay));
        RunnableScheduledFuture<Void> t = decorateTask(command, sft);
        sft.outerTask = t;
        delayedExecute(t);
        return t;
    }

    //使用所要求的零延遲執行命令
    public void execute(Runnable command) {
        schedule(command, 0, NANOSECONDS);
    }

    //提交一個 Runnable 任務用於執行,並返回一個表示該任務的 Future
    public Future<?> submit(Runnable task) {
        return schedule(task, 0, NANOSECONDS);
    }

    //提交一個 Runnable 任務用於執行,並返回一個表示該任務的 Future
    public <T> Future<T> submit(Runnable task, T result) {
        return schedule(Executors.callable(task, result), 0, NANOSECONDS);
    }

    //提交一個返回值的任務用於執行,返回一個表示任務的未決結果的 Future
    public <T> Future<T> submit(Callable<T> task) {
        return schedule(task, 0, NANOSECONDS);
    }

    //設定有關在此執行程式已shutdown的情況下是否繼續執行現有定期任務的策略
    public void setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean value) {
        continueExistingPeriodicTasksAfterShutdown = value;
        if (!value && isShutdown())
            onShutdown();
    }

    //獲取有關在此執行程式已shutdown的情況下、是否繼續執行現有定期任務的策略
    public boolean getContinueExistingPeriodicTasksAfterShutdownPolicy() {
        return continueExistingPeriodicTasksAfterShutdown;
    }

    //設定有關在此執行程式已shutdown的情況下是否繼續執行現有延遲任務的策略
    public void setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean value) {
        executeExistingDelayedTasksAfterShutdown = value;
        if (!value && isShutdown())
            onShutdown();
    }

    //獲取有關在此執行程式已shutdown的情況下是否繼續執行現有延遲任務的策略
    public boolean getExecuteExistingDelayedTasksAfterShutdownPolicy() {
        return executeExistingDelayedTasksAfterShutdown;
    }

    //設定移除策略
    public void setRemoveOnCancelPolicy(boolean value) {
        removeOnCancel = value;
    }

    //得到移除策略
    public boolean getRemoveOnCancelPolicy() {
        return removeOnCancel;
    }

    //在以前已提交任務的執行中發起一個有序的關閉,但是不接受新任務
    public void shutdown() {
        super.shutdown();
    }

    //嘗試停止所有正在執行的任務、暫停等待任務的處理,並返回等待執行的任務列表
    public List<Runnable> shutdownNow() {
        return super.shutdownNow();
    }

    //返回此執行程式使用的任務佇列
    public BlockingQueue<Runnable> getQueue() {
        return super.getQueue();
    }

    final long now() {
        return System.nanoTime();
    }

    boolean canRunInCurrentRunState(boolean periodic) {
        return isRunningOrShutdown(periodic ?
                continueExistingPeriodicTasksAfterShutdown :
                executeExistingDelayedTasksAfterShutdown);
    }


    private void delayedExecute(RunnableScheduledFuture<?> task) {
        if (isShutdown())
            reject(task);
        else {
            super.getQueue().add(task);
            if (isShutdown() &&
                    !canRunInCurrentRunState(task.isPeriodic()) &&
                    remove(task))
                task.cancel(false);
            else
                ensurePrestart();
        }
    }


    void reExecutePeriodic(RunnableScheduledFuture<?> task) {
        if (canRunInCurrentRunState(true)) {
            super.getQueue().add(task);
            if (!canRunInCurrentRunState(true) && remove(task))
                task.cancel(false);
            else
                ensurePrestart();
        }
    }


    @Override
    void onShutdown() {
        BlockingQueue<Runnable> q = super.getQueue();
        boolean keepDelayed =
                getExecuteExistingDelayedTasksAfterShutdownPolicy();
        boolean keepPeriodic =
                getContinueExistingPeriodicTasksAfterShutdownPolicy();
        if (!keepDelayed && !keepPeriodic) {
            for (Object e : q.toArray())
                if (e instanceof RunnableScheduledFuture<?>)
                    ((RunnableScheduledFuture<?>) e).cancel(false);
            q.clear();
        } else {
            for (Object e : q.toArray()) {
                if (e instanceof RunnableScheduledFuture) {
                    RunnableScheduledFuture<?> t =
                            (RunnableScheduledFuture<?>) e;
                    if ((t.isPeriodic() ? !keepPeriodic : !keepDelayed) ||
                            t.isCancelled()) { // also remove if already cancelled
                        if (q.remove(t))
                            t.cancel(false);
                    }
                }
            }
        }
        tryTerminate();
    }

    //修改或替換用於執行 runnable 的任務
    protected <V> RunnableScheduledFuture<V> decorateTask(
            Runnable runnable, RunnableScheduledFuture<V> task) {
        return task;
    }

    //修改或替換用於執行 callable 的任務
    protected <V> RunnableScheduledFuture<V> decorateTask(
            Callable<V> callable, RunnableScheduledFuture<V> task) {
        return task;
    }
}

 

類 ScheduledThreadPoolExecutor

所有已實現的介面:

    ExecutorExecutorServiceScheduledExecutorService

    在給定的延遲後執行命令,或者定期執行命令。需要多個輔助執行緒時,或者要求 ThreadPoolExecutor 具有額外的靈活性或功能時,此類要優於 Timer

    一旦啟用已延遲的任務就執行它,但是有關何時啟用,啟用後何時執行則沒有任何實時保證。按照提交的先進先出 (FIFO) 順序來啟用那些被安排在同一執行時間的任務。

    雖然此類繼承自 ThreadPoolExecutor,但是幾個繼承的調整方法對此類並無作用。特別是,因為它作為一個使用 corePoolSize 執行緒和一個無界佇列的固定大小的池,所以調整 maximumPoolSize 沒有什麼效果。

 

    擴充套件注意事項:此類重寫 AbstractExecutorService 的 submit 方法,以生成內部物件控制每個任務的延遲和排程。若要保留功能性,子類中任何進一步重寫的這些方法都必須呼叫超類版本,超類版本有效地禁用附加任務的定製。

    但是,此類提供替代受保護的擴充套件方法 decorateTask(為 Runnable 和 Callable 各提供一種版本),可定製用於通過 execute、submit、schedule、scheduleAtFixedRate 和 scheduleWithFixedDelay 進入的執行命令的具體任務型別。預設情況下,ScheduledThreadPoolExecutor 使用一個擴充套件 FutureTask 的任務型別。但是,可以使用下列形式的子類修改或替換該型別。

 public class CustomScheduledExecutor extends ScheduledThreadPoolExecutor {

   static class CustomTask<V> implements RunnableScheduledFuture<V> { ... }

   protected <V> RunnableScheduledFuture<V> decorateTask(
                Runnable r, RunnableScheduledFuture<V> task) {
       return new CustomTask<V>(r, task);
   }

   protected <V> RunnableScheduledFuture<V> decorateTask(
                Callable<V> c, RunnableScheduledFuture<V> task) {
       return new CustomTask<V>(c, task);
   }
   // ... add constructors, etc.
 }
 

 

從類 java.util.concurrent.ThreadPoolExecutor 繼承的巢狀類/介面

    ThreadPoolExecutor.AbortPolicy, ThreadPoolExecutor.CallerRunsPolicy, ThreadPoolExecutor.DiscardOldestPolicy, ThreadPoolExecutor.DiscardPolicy

 

構造方法摘要

ScheduledThreadPoolExecutor(int corePoolSize) 
          使用給定核心池大小建立一個新 ScheduledThreadPoolExecutor。
ScheduledThreadPoolExecutor(int corePoolSize, RejectedExecutionHandler handler) 
          使用給定初始引數建立一個新 ScheduledThreadPoolExecutor。
ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory) 
          使用給定的初始引數建立一個新 ScheduledThreadPoolExecutor。
ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler) 
          使用給定初始引數建立一個新 ScheduledThreadPoolExecutor。

 

從類 java.util.concurrent.ThreadPoolExecutor 繼承的方法

    afterExecute, allowCoreThreadTimeOut, allowsCoreThreadTimeOut, awaitTermination, beforeExecute, finalize,getActiveCount,getCompletedTaskCount, getCorePoolSize, getKeepAliveTime, getLargestPoolSize, getMaximumPoolSize, getPoolSize, getRejectedExecutionHandler, getTaskCount, getThreadFactory,isShutdown, isTerminated, isTerminating, prestartAllCoreThreads, prestartCoreThread, purge, setCorePoolSize, setKeepAliveTime, setMaximumPoolSize, setRejectedExecutionHandler, setThreadFactory, terminated

 從類 java.util.concurrent.AbstractExecutorService 繼承的方法

    invokeAll, invokeAll, invokeAny, invokeAny, newTaskFor, newTaskFor

 從類 java.lang.Object 繼承的方法

    clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

從介面 java.util.concurrent.ExecutorService 繼承的方法

    awaitTermination, invokeAll, invokeAll, invokeAny, invokeAny, isShutdown, isTerminated

 

ScheduledThreadPoolExecutor

public ScheduledThreadPoolExecutor(int corePoolSize)

    使用給定核心池大小建立一個新 ScheduledThreadPoolExecutor。

    引數:

    corePoolSize - 池中所儲存的執行緒數(包括空閒執行緒)

    丟擲:

    IllegalArgumentException - 如果 corePoolSize < 0

 

ScheduledThreadPoolExecutor

public ScheduledThreadPoolExecutor(int corePoolSize,
                                   ThreadFactory threadFactory)

    使用給定的初始引數建立一個新 ScheduledThreadPoolExecutor。

    引數:

    corePoolSize - 池中所儲存的執行緒數(包括空閒執行緒)

    threadFactory - 執行程式建立新執行緒時使用的工廠

    丟擲:

    IllegalArgumentException - 如果 corePoolSize < 0

    NullPointerException - 如果 threadFactory 為 null

 

ScheduledThreadPoolExecutor

public ScheduledThreadPoolExecutor(int corePoolSize,
                                   RejectedExecutionHandler handler)

    使用給定初始引數建立一個新 ScheduledThreadPoolExecutor。

    引數:

    corePoolSize - 池中所儲存的執行緒數(包括空閒執行緒)

    handler - 由於超出執行緒範圍和佇列容量而使執行被阻塞時所使用的處理程式

    丟擲:

    IllegalArgumentException - 如果 corePoolSize < 0

    NullPointerException - 如果處理程式為 null

 

ScheduledThreadPoolExecutor

public ScheduledThreadPoolExecutor(int corePoolSize,
                                   ThreadFactory threadFactory,
                                   RejectedExecutionHandler handler)

    使用給定初始引數建立一個新 ScheduledThreadPoolExecutor。

    引數:

    corePoolSize - 池中所儲存的執行緒數(包括空閒執行緒)

    threadFactory - 執行程式建立新執行緒時使用的工廠

    handler - 由於超出執行緒範圍和佇列容量而使執行被阻塞時所使用的處理程式

    丟擲:

    IllegalArgumentException - 如果 corePoolSize < 0

    NullPointerException - 如果 threadFactory 或處理程式為 null

 

remove

public boolean remove(Runnable task)

    從類 ThreadPoolExecutor 複製的描述

        從執行程式的內部佇列中移除此任務(如果存在),從而如果尚未開始,則其不再執行。

        此方法可用作取消方案的一部分。它可能無法移除在放置到內部佇列之前已經轉換為其他形式的任務。例如,使用 submit 輸入的任務可能被轉換為維護 Future 狀態的形式。但是,在此情況下,ThreadPoolExecutor.purge() 方法可用於移除那些已被取消的 Future。

    覆蓋:

        類 ThreadPoolExecutor 中的 remove

    引數:

    task - 要移除的任務

    返回:

        如果已經移除任務,則返回 true

 

decorateTask

protected <V> RunnableScheduledFuture<V> decorateTask(Runnable runnable,
                                                      RunnableScheduledFuture<V> task)

    修改或替換用於執行 runnable 的任務。此方法可重寫用於管理內部任務的具體類。預設實現只返回給定任務。

    引數:

    runnable - 所提交的 Runnable

    task - 執行 runnable 所建立的任務

    返回:

        可以執行 runnable 的任務

 

decorateTask

protected <V> RunnableScheduledFuture<V> decorateTask(Callable<V> callable,
                                                      RunnableScheduledFuture<V> task)

    修改或替換用於執行 callable 的任務。此方法可重寫用於管理內部任務的具體類。預設實現返回給定任務。

    引數:

    callable - 所提交的 Callable

    task - 執行 callable 所建立的任務

    返回:

        可以執行 callable 的任務

 

schedule

public ScheduledFuture<?> schedule(Runnable command,
                                   long delay,
                                   TimeUnit unit)

    從介面 ScheduledExecutorService 複製的描述

        建立並執行在給定延遲後啟用的一次性操作。

    指定者:

        介面 ScheduledExecutorService 中的 schedule

    引數:

    command - 要執行的任務

    delay - 從現在開始延遲執行的時間

    unit - 延遲引數的時間單位

    返回:

        表示掛起任務完成的 ScheduledFuture,並且其 get() 方法在完成後將返回 null

 

schedule

public <V> ScheduledFuture<V> schedule(Callable<V> callable,
                                       long delay,
                                       TimeUnit unit)

    從介面 ScheduledExecutorService 複製的描述

        建立並執行在給定延遲後啟用的 ScheduledFuture。

    指定者:

        介面 ScheduledExecutorService 中的 schedule

    引數:

    callable - 要執行的功能

    delay - 從現在開始延遲執行的時間

    unit - 延遲引數的時間單位

    返回:

        可用於提取結果或取消的 ScheduledFuture

 

scheduleAtFixedRate

public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                              long initialDelay,
                                              long period,
                                              TimeUnit unit)

    從介面 ScheduledExecutorService 複製的描述

        建立並執行一個在給定初始延遲後首次啟用的定期操作,後續操作具有給定的週期;也就是將在 initialDelay 後開始執行,然後在 initialDelay+period 後執行,接著在 initialDelay + 2 * period 後執行,依此類推。如果任務的任何一個執行遇到異常,則後續執行都會被取消。否則,只能通過執行程式的取消或終止方法來終止該任務。如果此任務的任何一個執行要花費比其週期更長的時間,則將推遲後續執行,但不會同時執行。

    指定者:

        介面 ScheduledExecutorService 中的 scheduleAtFixedRate

    引數:

    command - 要執行的任務

    initialDelay - 首次執行的延遲時間

    period - 連續執行之間的週期

    unit - initialDelay 和 period 引數的時間單位

    返回:

        表示掛起任務完成的 ScheduledFuture,並且其 get() 方法在取消後將丟擲異常

 

scheduleWithFixedDelay

public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                                 long initialDelay,
                                                 long delay,
                                                 TimeUnit unit)

    從介面 ScheduledExecutorService 複製的描述

        建立並執行一個在給定初始延遲後首次啟用的定期操作,隨後,在每一次執行終止和下一次執行開始之間都存在給定的延遲。如果任務的任一執行遇到異常,就會取消後續執行。否則,只能通過執行程式的取消或終止方法來終止該任務。

    指定者:

        介面 ScheduledExecutorService 中的 scheduleWithFixedDelay

    引數:

    command - 要執行的任務

    initialDelay - 首次執行的延遲時間

    delay - 一次執行終止和下一次執行開始之間的延遲

    unit - initialDelay 和 delay 引數的時間單位

    返回:

        表示掛起任務完成的 ScheduledFuture,並且其 get() 方法在取消後將丟擲異常

 

execute

public void execute(Runnable command)

    使用所要求的零延遲執行命令。這在效果上等同於呼叫 schedule(command, 0, anyUnit)。注意,對由 shutdownNow 所返回的佇列和列表的檢查將訪問零延遲的 ScheduledFuture,而不是 command 本身。

    指定者:

        介面 Executor 中的 execute

    覆蓋:

        類 ThreadPoolExecutor 中的 execute

    引數:

    command - 要執行的任務。

    丟擲:

        RejectedExecutionHandler 隨意決定的 RejectedExecutionException,如果由於執行程式已關閉而無法接受要執行的任務 。

   NullPointerException - 如果 command 為 null。

 

submit

public Future<?> submit(Runnable task)

    從介面 ExecutorService 複製的描述

        提交一個 Runnable 任務用於執行,並返回一個表示該任務的 Future。該 Future 的 get 方法在 成功 完成時將會返回 null。

    指定者:

        介面 ExecutorService 中的 submit

    覆蓋:

        類 AbstractExecutorService 中的 submit

    引數:

    task - 要提交的任務

    返回:

    表示任務等待完成的 Future

 

submit

public <T> Future<T> submit(Runnable task,T result)

    從介面 ExecutorService 複製的描述

        提交一個 Runnable 任務用於執行,並返回一個表示該任務的 Future。該 Future 的 get 方法在成功完成時將會返回給定的結果。

    指定者:

        介面