Java 简明教程

Java - Scheduling Threads with Examples

Java 是一种多线程编程语言,这意味着我们可以使用 Java 开发多线程程序。多线程程序包含两个或更多可以同时运行的部分,每个部分都可以在同一时间处理不同的任务,从而优化利用可用资源,特别是在您的计算机有多个 CPU 时。

Java is a multi-threaded programming language which means we can develop multi-threaded program using Java. A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs.

根据定义,多任务处理是多个进程共享公共处理资源(如 CPU)时发生的情况。多线程将多任务处理的概念扩展到应用程序中,您可以在其中将单个应用程序内的特定操作细分为各个线程。每个线程都可以并行运行。操作系统不仅在不同应用程序之间划分处理时间,还在应用程序内的每个线程之间划分处理时间。

By definition, multitasking is when multiple processes share common processing resources such as a CPU. Multi-threading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application.

通过使用多线程,您可以以在相同程序中可以并行执行多项活动的方式来编写代码。

Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the same program.

Java 提供了 java.util.concurrent.ScheduledExecutorService 接口,这是 ExecutorService 接口的一个子接口,支持任务/线程的将来执行和/或周期性执行。以下是此接口中的一些重要且有用的方法。

Java provides a java.util.concurrent.ScheduledExecutorService interface which is a subinterface of ExecutorService interface, and supports future and/or periodic execution of tasks/threads. Following are few important and useful methods this interface.

ScheduledExecutorService Methods

Sr.No.

Method & Description

1

<V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) Creates and executes a ScheduledFuture that becomes enabled after the given delay.

2

ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) Creates and executes a one-shot action that becomes enabled after the given delay.

3

ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) Creates and executes 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.

4

ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) Creates and executes 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.

Example 1

TestThread 程序通过定期根据日程执行任务(在 10 秒的时间段内,每隔 2 秒执行一次,持续 2 秒)来演示在基于线程的环境中使用 ScheduledExecutorService 接口,展示了 scheduleAtFixedRate() 和 schedule() 方法的使用情况。

The following TestThread program shows usage of ScheduledExecutorService interface in thread based environment to schedule a task to run after 2 seconds at interval of 2 seconds in time period of 10 seconds showcasing usage of scheduleAtFixedRate() and schedule() methods.

package com.tutorialspoint;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class TestThread {

   public static void main(final String[] arguments) throws InterruptedException {
      final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

      final ScheduledFuture<?> beepHandler =
         scheduler.scheduleAtFixedRate(new BeepTask(), 2, 2, TimeUnit.SECONDS);

      scheduler.schedule(new Runnable() {

         @Override
         public void run() {
            beepHandler.cancel(true);
            scheduler.shutdown();
         }
      }, 10, TimeUnit.SECONDS);
   }

   static class BeepTask implements Runnable {

      public void run() {
         System.out.println("beep");
      }
   }
}

Output

beep
beep
beep
beep
beep

Example 2

以下 TestThread 程序通过定期根据日程执行任务(在 10 秒的时间段内,每隔 2 秒执行一次,持续 2 秒)来演示在基于线程的环境中使用 ScheduledExecutorService 接口,展示了 scheduleAtFixedDelay() 和 schedule() 方法的使用情况。

The following TestThread program shows usage of ScheduledExecutorService interface in thread based environment to schedule a task to run after 2 seconds at interval of 2 seconds in time period of 10 seconds showcasing usage of scheduleAtFixedDelay() and schedule() methods.

package com.tutorialspoint;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class TestThread {

   public static void main(final String[] arguments) throws InterruptedException {
      final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

      final ScheduledFuture<?> beepHandler =
         scheduler.scheduleAtFixedDelay(new BeepTask(), 2, 2, TimeUnit.SECONDS);

      scheduler.schedule(new Runnable() {

         @Override
         public void run() {
            beepHandler.cancel(true);
            scheduler.shutdown();
         }
      }, 10, TimeUnit.SECONDS);
   }

   static class BeepTask implements Runnable {

      public void run() {
         System.out.println("beep");
      }
   }
}

Output

beep
beep
beep
beep

Example 3

TestThread 程序通过定期根据日程执行任务(在 10 秒的时间段内,2 秒后执行一次)来演示在基于线程的环境中使用 ScheduledExecutorService 接口,展示了 schedule() 方法的使用情况。

The following TestThread program shows usage of ScheduledExecutorService interface in thread based environment to schedule a task to run once after 2 seconds in time period of 10 seconds showcasing usage of schedule() method.

package com.tutorialspoint;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class TestThread {

   public static void main(final String[] arguments) throws InterruptedException {
      final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

      final ScheduledFuture<?> beepHandler =
         scheduler.schedule(new BeepTask(), 2, TimeUnit.SECONDS);

      scheduler.schedule(new Runnable() {

         @Override
         public void run() {
            beepHandler.cancel(true);
            scheduler.shutdown();
         }
      }, 10, TimeUnit.SECONDS);
   }

   static class BeepTask implements Runnable {

      public void run() {
         System.out.println("beep");
      }
   }
}

Output

beep