【Java】了解线程 Thread 类的使用,如何创建、终止、等待一个线程以及获取线程的状态
创建线程:
// 方法一:继承Thread类
public class MyThread extends Thread {
public void run(){
System.out.println("线程开始执行");
}
}
// 创建并启动线程
MyThread myThread = new MyThread();
myThread.start();
// 方法二:实现Runnable接口
public class MyRunnable implements Runnable {
public void run(){
System.out.println("线程开始执行");
}
}
// 创建并启动线程
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
终止线程:
// 通常不建议直接终止线程,而是使用标志位来优雅地结束线程
public class ControlledThread extends Thread {
private volatile boolean running = true;
public void run(){
while (running) {
// 执行任务
}
}
public void stopRunning(){
running = false;
}
}
ControlledThread controlledThread = new ControlledThread();
controlledThread.start();
// 当需要终止线程时
controlledThread.stopRunning();
等待线程:
Thread thread = new Thread(myRunnable);
thread.start();
// 等待线程终止
thread.join();
获取当前线程:
Thread currentThread = Thread.currentThread();
currentThread.getName(); // 获取线程名称
评论已关闭