【Java】了解线程 Thread 类的使用,如何创建、终止、等待一个线程以及获取线程的状态
原创Java中线程Thread类的使用
在Java编程语言中,线程可以通过扩展java.lang.Thread类或实现Runnable接口来创建。使用Thread类是创建并发线程的一种直接做法。以下将介绍怎样使用Thread类创建、终止、等待线程以及获取线程的状态。
1. 创建线程
创建线程可以通过以下两种方法:
1.1 通过扩展Thread类
public class MyThread extends Thread {
public void run() {
// 线程执行的代码
System.out.println("线程运行中...");
}
}
// 使用方法
public class TestThread {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start(); // 启动线程
}
}
1.2 通过实现Runnable接口
public class MyRunnable implements Runnable {
public void run() {
// 线程执行的代码
System.out.println("线程运行中...");
}
}
// 使用方法
public class TestRunnable {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start(); // 启动线程
}
}
2. 终止线程
Java没有提供直接终止线程的方法,但是可以通过以下做法来间接终止线程:
- 通过设置一个标志位,使线程正常退出:
public class MyRunnable implements Runnable {
private volatile boolean isRunning = true;
public void run() {
while (isRunning) {
// 执行任务...
}
}
public void stopThread() {
isRunning = false;
}
}
- 使用中断机制:
public class MyThread extends Thread {
public void run() {
while (!isInterrupted()) {
// 执行任务...
}
// 清理资源或执行其他操作
}
}
// 终止线程
myThread.interrupt();
3. 等待线程
可以使用join方法等待一个线程的终止。当前线程会等待直到指定线程终止:
public class TestJoin {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new MyRunnable());
thread.start();
thread.join(); // 等待thread线程终止
System.out.println("主线程继续执行...");
}
}
4. 获取线程的状态
Thread类提供了getState方法,可以用来获取当前线程的状态:
public class TestState {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new MyRunnable());
thread.start();
Thread.State state = thread.getState();
System.out.println("线程当前状态:" + state);
// 在一段时间后获取状态
Thread.sleep(1000);
state = thread.getState();
System.out.println("线程当前状态:" + state);
}
}
线程的也许状态包括:NEW(新建)、RUNNABLE(可运行)、BLOCKED(阻塞)、WAITING(等待)、TIMED_WAITING(计时等待)、TERMINATED(终止)。
以上就是使用Java的Thread类创建、终止、等待线程以及获取线程状态的基本方法。