Java - 多线程
Java 是一种多线程编程语言 这意味着我们可以使用 Java 开发多线程程序。多线程程序包含两个或多个可以同时运行的部分,每个部分可以同时处理不同的任务,从而优化利用可用资源,特别是当您的计算机具有多个 CPU 时。
根据定义,多任务处理是指多个进程共享公共处理资源(例如 CPU)。多线程将多任务的概念扩展到应用程序中,您可以将单个应用程序中的特定操作细分为单独的线程。每个线程都可以并行运行。操作系统不仅在不同的应用程序之间分配处理时间,而且在应用程序内的每个线程之间分配处理时间。
多线程使您能够以一种可以在同一个程序中同时进行多个活动的方式进行编写。
线程的生命周期
线程在其生命周期中经历不同的阶段。例如,一个线程诞生、启动、运行,然后死亡。下图展示了一个线程的完整生命周期。
以下是生命周期的各个阶段 -
-
新 − 新线程以新状态开始其生命周期。它一直保持这种状态,直到程序启动线程。它也被称为天生线程 .
-
可运行 − 新生成的线程启动后,该线程变为可运行的。处于这种状态的线程被认为正在执行它的任务。
-
等待 − 有时,一个线程在等待另一个线程执行任务时转换到等待状态。只有当另一个线程通知等待线程继续执行时,一个线程才会转换回可运行状态。
-
定时等待 − 可运行线程可以在指定的时间间隔内进入定时等待状态。当该时间间隔到期或它正在等待的事件发生时,处于此状态的线程将转换回可运行状态。
-
终止(死亡) − 可运行线程在完成其任务或以其他方式终止时进入终止状态。
线程优先级
每个 Java 线程都有一个优先级,可以帮助操作系统确定线程的调度顺序。
Java 线程优先级在 MIN_PRIORITY(常量 1)和 MAX_PRIORITY(常量 10)之间的范围内。默认情况下,每个线程都有优先级 NORM_PRIORITY(常量 5)。
具有较高优先级的线程对程序更重要,应在较低优先级线程之前分配处理器时间。但是,线程优先级并不能保证线程执行的顺序,并且非常依赖于平台。
通过实现可运行接口创建线程
如果您的类打算作为线程执行,那么您可以通过实现 Runnable 来实现 界面。您将需要遵循三个基本步骤 -
步骤 1
作为第一步,您需要实现 Runnable 提供的 run() 方法 界面。此方法为线程提供了一个入口点,您将把完整的业务逻辑放入此方法中。以下是 run() 方法的简单语法 -
public void run( )
第二步
第二步,您将实例化一个 Thread 使用以下构造函数的对象 -
Thread(Runnable threadObj, String threadName);
其中,threadObj 是实现 Runnable 的类的实例 接口和 threadName 是赋予新线程的名称。
第三步
创建 Thread 对象后,您可以通过调用 start() 来启动它 方法,它执行对 run() 方法的调用。以下是 start() 方法的简单语法 -
void start();
示例
这是一个创建新线程并开始运行它的示例 -
现场演示
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();
}
}
这将产生以下结果 -
输出
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.
通过扩展线程类创建线程
第二种创建线程的方法是创建一个扩展 Thread 的新类 类使用以下两个简单步骤。这种方法在处理使用 Thread 类中的可用方法创建的多个线程时提供了更大的灵活性。
步骤 1
您将需要覆盖 run( ) Thread 类中可用的方法。此方法为线程提供了一个入口点,您将把完整的业务逻辑放入此方法中。以下是 run() 方法的简单语法 -
public void run( )
第二步
创建 Thread 对象后,您可以通过调用 start() 来启动它 方法,它执行对 run() 方法的调用。以下是 start() 方法的简单语法 -
void start( );
示例
这是前面的程序重写以扩展线程 -
现场演示
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();
}
}
这将产生以下结果 -
输出
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.
线程方法
以下是 Thread 类中可用的重要方法列表。
| Sr.No. | 方法和说明 |
|---|---|
| 1 | public void start() 在单独的执行路径中启动线程,然后调用此 Thread 对象的 run() 方法。 |
| 2 | 公共无效运行() 如果此 Thread 对象是使用单独的 Runnable 目标实例化的,则会在该 Runnable 对象上调用 run() 方法。 |
| 3 | public final void setName(String name) 更改 Thread 对象的名称。还有一个 getName() 方法用于检索名称。 |
| 4 | public final void setPriority(int priority) 设置此 Thread 对象的优先级。可能的值在 1 到 10 之间。 |
| 5 | public final void setDaemon(boolean on) 参数为 true 表示此 Thread 为守护线程。 |
| 6 | public final void join(long millisec) 当前线程在第二个线程上调用此方法,导致当前线程阻塞,直到第二个线程终止或经过指定的毫秒数。 |
| 7 | 公共无效中断() 中断该线程,使其在因任何原因被阻塞时继续执行。 |
| 8 | public final boolean isAlive() 如果线程处于活动状态,则返回 true,即线程启动后但运行完成之前的任何时间。 |
前面的方法是在特定的 Thread 对象上调用的。 Thread 类中的以下方法是静态的。调用其中一个静态方法对当前运行的线程执行操作。
| Sr.No. | 方法和说明 |
|---|---|
| 1 | public static void yield() 使当前运行的线程让步给任何其他等待调度的具有相同优先级的线程。 |
| 2 | 公共静态无效睡眠(长毫秒) 使当前运行的线程至少阻塞指定的毫秒数。 |
| 3 | public static boolean holdLock(Object x) 如果当前线程持有给定 Object 的锁,则返回 true。 |
| 4 | 公共静态线程 currentThread() 返回对当前运行线程的引用,也就是调用该方法的线程。 |
| 5 | public static void dumpStack() 打印当前运行线程的堆栈跟踪,这在调试多线程应用程序时很有用。 |
示例
下面的 ThreadClassDemo 程序演示了 Thread 类的其中一些方法。考虑一个类 DisplayMessage 它实现了 Runnable -
// File Name : DisplayMessage.java
// Create a thread to implement Runnable
public class DisplayMessage implements Runnable {
private String message;
public DisplayMessage(String message) {
this.message = message;
}
public void run() {
while(true) {
System.out.println(message);
}
}
}
以下是另一个扩展 Thread 类的类 -
// File Name : GuessANumber.java
// Create a thread to extentd Thread
public class GuessANumber extends Thread {
private int number;
public GuessANumber(int number) {
this.number = number;
}
public void run() {
int counter = 0;
int guess = 0;
do {
guess = (int) (Math.random() * 100 + 1);
System.out.println(this.getName() + " guesses " + guess);
counter++;
} while(guess != number);
System.out.println("** Correct!" + this.getName() + "in" + counter + "guesses.**");
}
}
以下是主程序,它利用了上面定义的类 -
// File Name : ThreadClassDemo.java
public class ThreadClassDemo {
public static void main(String [] args) {
Runnable hello = new DisplayMessage("Hello");
Thread thread1 = new Thread(hello);
thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("Starting hello thread...");
thread1.start();
Runnable bye = new DisplayMessage("Goodbye");
Thread thread2 = new Thread(bye);
thread2.setPriority(Thread.MIN_PRIORITY);
thread2.setDaemon(true);
System.out.println("Starting goodbye thread...");
thread2.start();
System.out.println("Starting thread3...");
Thread thread3 = new GuessANumber(27);
thread3.start();
try {
thread3.join();
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 = new GuessANumber(75);
thread4.start();
System.out.println("main() is ending...");
}
}
这将产生以下结果。你可以反复尝试这个例子,每次都会得到不同的结果。
输出
Starting hello thread... Starting goodbye thread... Hello Hello Hello Hello Hello Hello Goodbye Goodbye Goodbye Goodbye Goodbye .......
主要的 Java 多线程概念
在 Java 中进行多线程编程时,您需要非常方便地掌握以下概念 -
-
什么是线程同步?
-
处理线程间通信
-
处理线程死锁
-
主要线程操作
java