📜  Java中的 ScheduledThreadPoolExecutor 类

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

Java中的 ScheduledThreadPoolExecutor 类

Java中的 ScheduledThreadPoolExecutor 类是Java.util.concurrent 包中定义的 ThreadPoolExecutor 类的子类。从它的名字可以清楚地看出,当我们想要安排任务重复运行或在给定的延迟后运行一段时间后运行时,这个类很有用。它创建一个固定大小的线程池。所以在启动的时候需要给它corePoolSize(Thread pool中的线程数)。

类层次结构:

ScheduledThreadPoolExecutor-Java 中的类

构造函数:

  • ScheduledThreadPoolExecutor(int corePoolSize) :使用给定的池大小创建一个新的 ScheduledThreadPoolExecutor 对象。需要注意的是,它创建了一个固定大小的线程池,因此一旦给定了 corePoolSize,就无法增加线程池的大小。
  • ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory) :使用给定参数创建一个新的 ScheduledThreadPoolExecutor 对象。第一个参数是线程池的大小,第二个参数是一个 ThreadFactory 对象,当 ScheduledThreadPoolExecutor 创建一个新线程时使用。
  • ScheduledThreadPoolExecutor(int corePoolSize, RejectedExecutionHandler handler) :使用给定的 corePoolSize(ThreadPool size) 创建一个新的 ScheduledThreadPoolExecutor 对象,以及在拒绝执行任务时使用的处理程序(当工作队列已满或执行被阻止时)。
  • ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler) :使用给定参数创建一个新的 ScheduledThreadPoolExecutor 对象。

除了这些构造函数之外,还有另一种获取 ScheduledThreadPoolExecutor 对象的方法。我们可以使用Executors 类定义的 Executors.newScheduledThreadPool(int corePoolSize)工厂方法。它返回一个 ScheduledExecutorService 对象,该对象可以类型转换为 ScheduledThreadPoolExecutor 对象。

示例 1

Java
// Java program to demonstrates ScheduleThreadPoolExecutor
// class
import java.util.*;
import java.util.concurrent.*;
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Creating a ScheduledThreadPoolExecutor object
        ScheduledThreadPoolExecutor threadPool
            = new ScheduledThreadPoolExecutor(2);
  
        // Creating two Runnable objects
        Runnable task1 = new Command("task1");
        Runnable task2 = new Command("task2");
  
        // Printing the current time in seconds
        System.out.println(
            "Current time : "
            + Calendar.getInstance().get(Calendar.SECOND));
  
        // Scheduling the first task which will execute
        // after 2 seconds
        threadPool.schedule(task1, 2, TimeUnit.SECONDS);
  
        // Scheduling the second task which will execute
        // after 5 seconds
        threadPool.schedule(task2, 5, TimeUnit.SECONDS);
  
        // Remember to shut sown the Thread Pool
        threadPool.shutdown();
    }
}
  
// Class that implements the Runnable interface
class Command implements Runnable {
    String taskName;
    public Command(String taskName)
    {
        this.taskName = taskName;
    }
    public void run()
    {
        System.out.println(
            "Task name : " + this.taskName + " Current time: "
            + Calendar.getInstance().get(Calendar.SECOND));
    }
}


Java
// Java program to demonstrates ScheduleThreadPoolExecutor
// class
import java.util.*;
import java.util.concurrent.*;
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Creating a ScheduledThreadPoolExecutor object
        ScheduledThreadPoolExecutor threadPool
            = new ScheduledThreadPoolExecutor(2);
  
        // Creating two Runnable objects
        Runnable task1 = new Command("task1");
        Runnable task2 = new Command("task2");
  
        // Printing the current time in seconds
        System.out.println(
            "Current time:"
            + Calendar.getInstance().get(Calendar.SECOND));
  
        // Scheduling the first task which will execute
        // after 2 seconds and then repeats periodically with
        // a period of 8 seconds
        threadPool.scheduleAtFixedRate(task1, 2, 8,
                                       TimeUnit.SECONDS);
  
        // Scheduling the second task which will execute
        // after 5 seconds and then there will be a delay of
        // 5 seconds between the completion
        // of one execution and the commencement of the next
        // execution
        threadPool.scheduleWithFixedDelay(task2, 5, 5,
                                          TimeUnit.SECONDS);
  
        // Wait for 30 seconds
        try {
            Thread.sleep(30000);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
  
        // Remember to shut sown the Thread Pool
        threadPool.shutdown();
    }
}
  
// Class that implements Runnable interface
class Command implements Runnable {
    String taskName;
    public Command(String taskName)
    {
        this.taskName = taskName;
    }
    public void run()
    {
        try {
            System.out.println("Task name : "
                               + this.taskName
                               + " Current time : "
                               + Calendar.getInstance().get(
                                     Calendar.SECOND));
            Thread.sleep(2000);
            System.out.println("Executed : " + this.taskName
                               + " Current time : "
                               + Calendar.getInstance().get(
                                     Calendar.SECOND));
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}


输出

Current time : 51
Task name : task1 Current time : 53
Task name : task2 Current time : 56

这里第一个任务在两秒延迟后执行,第二个任务在五秒后执行。

示例2

Java

// Java program to demonstrates ScheduleThreadPoolExecutor
// class
import java.util.*;
import java.util.concurrent.*;
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Creating a ScheduledThreadPoolExecutor object
        ScheduledThreadPoolExecutor threadPool
            = new ScheduledThreadPoolExecutor(2);
  
        // Creating two Runnable objects
        Runnable task1 = new Command("task1");
        Runnable task2 = new Command("task2");
  
        // Printing the current time in seconds
        System.out.println(
            "Current time:"
            + Calendar.getInstance().get(Calendar.SECOND));
  
        // Scheduling the first task which will execute
        // after 2 seconds and then repeats periodically with
        // a period of 8 seconds
        threadPool.scheduleAtFixedRate(task1, 2, 8,
                                       TimeUnit.SECONDS);
  
        // Scheduling the second task which will execute
        // after 5 seconds and then there will be a delay of
        // 5 seconds between the completion
        // of one execution and the commencement of the next
        // execution
        threadPool.scheduleWithFixedDelay(task2, 5, 5,
                                          TimeUnit.SECONDS);
  
        // Wait for 30 seconds
        try {
            Thread.sleep(30000);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
  
        // Remember to shut sown the Thread Pool
        threadPool.shutdown();
    }
}
  
// Class that implements Runnable interface
class Command implements Runnable {
    String taskName;
    public Command(String taskName)
    {
        this.taskName = taskName;
    }
    public void run()
    {
        try {
            System.out.println("Task name : "
                               + this.taskName
                               + " Current time : "
                               + Calendar.getInstance().get(
                                     Calendar.SECOND));
            Thread.sleep(2000);
            System.out.println("Executed : " + this.taskName
                               + " Current time : "
                               + Calendar.getInstance().get(
                                     Calendar.SECOND));
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

输出

Current time:26
Task name : task1 Current time : 28
Executed : task1 Current time : 30
Task name : task2 Current time : 31
Executed : task2 Current time : 33
Task name : task1 Current time : 36
Executed : task1 Current time : 38
Task name : task2 Current time : 38
Executed : task2 Current time : 40
Task name : task1 Current time : 44
Task name : task2 Current time : 45
Executed : task1 Current time : 46
Executed : task2 Current time : 47
Task name : task1 Current time : 52
Task name : task2 Current time : 52
Executed : task1 Current time : 54
Executed : task2 Current time : 54

在这里,第一个任务将在两秒后执行,然后在八秒后定期重复。第二个任务将在五秒钟后执行,然后在一次执行完成和下一次执行开始之间会有五秒钟的延迟。

方法

METHOD

DESCRIPTION

decorateTask(Callable callable, RunnableScheduledFuture task)Modifies or replaces the task used to execute a callable.
decorateTask(Runnable runnable, RunnableScheduledFuture task)Modifies or replaces the task used to execute a runnable.
execute(Runnable command)Executes command with zero required delay.
getContinueExistingPeriodicTasksAfterShutdownPolicy( )Get the policy on whether to continue executing existing periodic tasks even when this executor has been shut down.
getExecuteExistingDelayedTasksAfterShutdownPolicy( )Get the policy on whether to execute existing delayed tasks even when this executor has been shut down.
getQueue()Returns the task queue used by this executor.
getRemoveOnCancelPolicy()Gets the policy on whether cancelled tasks should be immediately removed from the work queue at the time of cancellation.
schedule(Callable callable, long delay, TimeUnit unit)Creates and executes a ScheduledFuture that becomes enabled after the given delay.
schedule(Runnable command, long delay, TimeUnit unit)Creates and executes a one-shot action that becomes enabled after the given delay.
scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)Creates and executes a periodic action that becomes enabled first after the given delay and subsequently with the given period.
scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)Creates and executes a periodic action that becomes enabled after the given delay and subsequently with the given delay between the termination of one execution and commencement of the next execution.
setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean value)Sets the policy on whether to continue executing existing periodic tasks even when this executor has been shut down.
setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean value)Sets the policy on whether to execute existing delayed tasks even when this executor has been shut down.
setRemoveOnCancelPolicy()Sets the policy on whether cancelled tasks should be immediately removed from the work queue at the time of cancellation.
shutdown()Initiate 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(Callable task)Submits a value returning task for execution and returns a future representing the pending results of the task.
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.