📜  Java中的 ScheduledExecutorService 接口

📅  最后修改于: 2022-05-13 01:54:37.080000             🧑  作者: Mango

Java中的 ScheduledExecutorService 接口

Java中的ScheduledExecutorService接口是Java.util.concurrent包中定义的 ExecutorService 接口的子接口。此接口用于定期或在给定延迟后运行给定任务。 ScheduledExecutorService 接口声明了一些有用的方法来调度给定的任务。这些方法由 ScheduledThreadPoolExecutor 类实现。

宣言

public interface ScheduledExecutorService extends ExecutorService

ScheduledExecutorService 的层次结构

Java 中的 ScheduledExecutorService 接口

实现类

ScheduledExecutorService 的实现类是 ScheduledThreadPoolExecutor。

创建 ScheduledExecutorService 对象

由于 ScheduledExecutorService 是一个接口,所以它不能被实例化。但是在Java.util.concurrent包中定义的Executors类提供了一些返回 ScheduledExecutorService 对象(其实现类的对象)的工厂方法

  • public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) :使用给定的核心池大小( corePoolSize )创建一个新的调度线程池,并返回一个 ScheduledExecutorService 对象,该对象可以向下转换为 ScheduledThreadPoolExecutor 对象。此对象可用于在给定延迟后运行任务或定期执行。
  • public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize , ThreadFactory threadFactory) :创建一个具有给定核心池大小 (corePoolSize) 的新调度线程池,并返回一个 ScheduledExecutorService 对象,该对象可以向下转换为 ScheduledThreadPoolExecutor 对象。第二个参数是创建新线程时使用的 ThreadFactory 对象。

ScheduledExecutorService 接口示例

Java
// Java Program to demonstrate
// SchedulerExecutorService
  
import java.util.concurrent.*;
import java.util.*;
import java.io.*;
  
class SchedulerExecutorServiceExample {
    
    public static void main(String[] args)
    {
        System.out.println(
            "A count-down-clock program that counts from 10 to 0");
  
        // creating a ScheduledExecutorService object
        ScheduledExecutorService scheduler
            = Executors.newScheduledThreadPool(11);
  
        // printing the current time
        System.out.println(
            "Current time : "
            + Calendar.getInstance().get(Calendar.SECOND));
  
        // Scheduling the tasks
        for (int i = 10; i >= 0; i--) {
            scheduler.schedule(new Task(i), 10 - i,
                               TimeUnit.SECONDS);
        }
  
        // remember to shutdown the scheduler
        // so that it no longer accepts
          // any new tasks
        scheduler.shutdown();
    }
}
  
class Task implements Runnable {
    private int num;
    public Task(int num) { this.num = num; }
    public void run()
    {
        System.out.println(
            "Number " + num + " Current time : "
            + Calendar.getInstance().get(Calendar.SECOND));
    }
}


输出:

A count-down-clock program that counts from 10 to 0
Current time : 28
Number 10 Current time : 28
Number 9 Current time : 29
Number 8 Current time : 30
Number 7 Current time : 31
Number 6 Current time : 32
Number 5 Current time : 33
Number 4 Current time : 34
Number 3 Current time : 35
Number 2 Current time : 36
Number 1 Current time : 37
Number 0 Current time : 38

这是一个从 10 到 0 计数的倒计时时钟。 ScheduledExexutorService 对象即;调度程序是使用Executors.newScheduledThreadPool(int corePoolSize)方法创建的。

注意:在调用schedule()方法后(10 – i)秒延迟后执行的所有任务。当前时间的值可能会根据执行时间在输出中有所不同。

ScheduledExecutorService 的方法

METHOD

DESCRIPTION

schedule(Runnable command, long delay, TimeUnit unit)Submits a one-shot task that becomes enabled after the given delay.
schedule​(Callable callable, long delay, TimeUnit unit)Submits a value-returning one-shot task that becomes enabled after the given delay.
scheduleAtFixedRate​(Runnable command, long initialDelay, long period, TimeUnit unit)Submits a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is, executions will commence after initialDelay, then initialDelay + period, then initialDelay + 2 * period, and so on.
scheduleWithFixedDelay​(Runnable command, long initialDelay, long delay, TimeUnit unit)Submits a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next.

在接口Java.util.concurrent.Executor 中声明的方法

METHOD

DESCRIPTION

execute​(Runnable command)Executes the given command at some time in the future.

在接口Java.util.concurrent.ExecutorService 中声明的方法

METHOD

DESCRIPTION

awaitTermination​(long timeout, TimeUnit unit)Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.
invokeAll​(Collection> tasks)Executes the given tasks, returning a list of Futures holding their status and results when all complete.
invokeAll​(Collection> tasks, long timeout, TimeUnit unit)Executes the given tasks, returning a list of Futures holding their status and results when all complete or the timeout expires, whichever happens first.
invokeAny​(Collection> tasks)Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do.
invokeAny​(Collection> tasks, long timeout, TimeUnit unit)Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do before the given timeout elapses.
isShutdown()Returns true if this executor has been shut down.
isTerminated()Returns true if all tasks have completed following shut down.
shutdown()Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.
shutdownNow()Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
submit​(Runnable task)Submits a Runnable task for execution and returns a Future representing that task.
submit​(Runnable task, T result)Submits a Runnable task for execution and returns a Future representing that task.
submit​(Callable task)Submits a value-returning task for execution and returns a Future representing the pending results of the task.