Java Concurrency 简明教程

Java Concurrency - Overview

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.

Life Cycle of a Thread

线程在其生命周期中经过不同的阶段。例如,一个线程诞生、启动、运行,然后死亡。下图显示了线程的完整生命周期。

A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The following diagram shows the complete life cycle of a thread.

Thread Life Cycle

以下是生命周期的阶段 -

Following are the stages of the life cycle −

  1. New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.

  2. Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.

  3. Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.

  4. Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.

  5. Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates.

Thread Priorities

每个 Java 线程都有一个优先级,这有助于操作系统确定线程调度的顺序。

Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.

Java 线程优先级介于 MIN_PRIORITY(常量为 1)和 MAX_PRIORITY(常量为 10)之间。默认情况下,每个线程都获得 NORM_PRIORITY(常量为 5)优先级。

Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).

具有较高优先级的线程对程序而言更为重要,并且应该在较低优先级的线程之前分配处理器时间。但是,线程优先级不能保证线程执行的顺序,并且很大程度上取决于平台。

Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and are very much platform dependent.

Create a Thread by Implementing a Runnable Interface

如果准备将您的类作为线程执行,那么可以通过实现 Runnable 接口实现此目的。您需要遵循三个基本步骤 −

If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable interface. You will need to follow three basic steps −

Step 1

第一步,您需要实现 Runnable 接口提供的 run() 方法。此方法为线程提供了一个入口点,您需要将完整业务逻辑放入此方法内。以下是 run() 方法的一个简单语法:

As a first step, you need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of the run() method −

public void run( )

Step 2

作为第二步,您将使用以下构造函数实例化一个 Thread 对象 −

As a second step, you will instantiate a Thread object using the following constructor −

Thread(Runnable threadObj, String threadName);

其中,threadObj 是实现 Runnable 接口的类的实例,threadName 是赋予新线程的名称。

Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread.

Step 3

一旦创建了 Thread 对象,就可以通过调用 start() 方法来启动它,它执行对 run( ) 方法的调用。以下是 start() 方法的简单语法 -

Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method −

void start();

Example

下面是创建一个新线程并开始运行它的示例:

Here is an example that creates a new thread and starts running it −

class RunnableDemo implements Runnable {
   private Thread t;
   private String threadName;

   RunnableDemo(String name) {
      threadName = name;
      System.out.println("Creating " +  threadName );
   }

   public void run() {
      System.out.println("Running " +  threadName );

      try {

         for(int i = 4; i > 0; i--) {
            System.out.println("Thread: " + threadName + ", " + i);

            // Let the thread sleep for a while.
            Thread.sleep(50);
         }
      } catch (InterruptedException e) {
         System.out.println("Thread " +  threadName + " interrupted.");
      }
      System.out.println("Thread " +  threadName + " exiting.");
   }

   public void start () {
      System.out.println("Starting " +  threadName );

      if (t == null) {
         t = new Thread (this, threadName);
         t.start ();
      }
   }
}

public class TestThread {

   public static void main(String args[]) {
      RunnableDemo R1 = new RunnableDemo("Thread-1");
      R1.start();

      RunnableDemo R2 = new RunnableDemo("Thread-2");
      R2.start();
   }
}

这会产生以下结果 −

This will produce the following result −

Output

Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

Create a Thread by Extending a Thread Class

创建线程的第二种方法是创建一个扩展 Thread 类的类,使用以下两个简单步骤。这种方法在使用 Thread 类中可用方法创建多个线程时提供了更多的灵活性。

The second way to create a thread is to create a new class that extends Thread class using the following two simple steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class.

Step 1

您需要覆盖 Thread 类中可用的 run( ) 方法。此方法为线程提供一个入口点,您将把您的完整业务逻辑放在这个方法中。以下是 run() 方法的简单语法:

You will need to override run( ) method available in Thread class. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of run() method −

public void run( )

Step 2

一旦创建 Thread 对象,便可以通过调用 start() 方法来启动它,该调用会执行一个 run( ) 方法调用。以下是 start() 方法的一个简单语法 −

Once Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method −

void start( );

Example

以下是按照 Thread 扩展重写的先前程序:

Here is the preceding program rewritten to extend the Thread −

class ThreadDemo extends Thread {
   private Thread t;
   private String threadName;

   ThreadDemo(String name) {
      threadName = name;
      System.out.println("Creating " +  threadName );
   }

   public void run() {
      System.out.println("Running " +  threadName );

      try {

         for(int i = 4; i > 0; i--) {
            System.out.println("Thread: " + threadName + ", " + i);

            // Let the thread sleep for a while.
            Thread.sleep(50);
         }
      } catch (InterruptedException e) {
         System.out.println("Thread " +  threadName + " interrupted.");
      }
      System.out.println("Thread " +  threadName + " exiting.");
   }

   public void start () {
      System.out.println("Starting " +  threadName );

      if (t == null) {
         t = new Thread (this, threadName);
         t.start ();
      }
   }
}

public class TestThread {

   public static void main(String args[]) {
      ThreadDemo T1 = new ThreadDemo("Thread-1");
      T1.start();

      ThreadDemo T2 = new ThreadDemo("Thread-2");
      T2.start();
   }
}

这会产生以下结果 −

This will produce the following result −

Output

Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.