1. 使用标志位
可以定义一个布尔类型的标志位,在线程的 run()
方法中根据这个标志位来控制线程是否继续执行。当需要停止线程时,将标志位设置为 false
。
以下是使用标志位停止线程的示例代码:
class MyThread extends Thread {
// 定义标志位
private volatile boolean isRunning = true;
@Override
public void run() {
while (isRunning) {
// 线程执行的任务
System.out.println("线程正在执行...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("线程已停止");
}
// 停止线程的方法
public void stopThread() {
isRunning = false;
}
}
public class StopThreadByFlag {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
try {
// 线程执行 5 秒后停止
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.stopThread();
}
}
在上述代码中,isRunning
是一个标志位,run()
方法会根据这个标志位来决定是否继续执行。当调用 stopThread()
方法时,将 isRunning
设置为 false
,线程就会停止执行。
2. 使用 interrupt()
方法
interrupt()
方法可以用来中断线程。当调用线程的 interrupt()
方法时,会设置线程的中断标志位。线程可以通过检查这个标志位来决定是否停止执行。
以下是使用 interrupt()
方法停止线程的示例代码:
class MyThread extends Thread {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// 线程执行的任务
System.out.println("线程正在执行...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// 当线程在休眠时被中断,会抛出 InterruptedException
Thread.currentThread().interrupt();
}
}
System.out.println("线程已停止");
}
}
public class StopThreadByInterrupt {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
try {
// 线程执行 5 秒后停止
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
}
}
在上述代码中,run()
方法通过 Thread.currentThread().isInterrupted()
来检查线程的中断标志位。当调用 interrupt()
方法时,会设置中断标志位,线程会检查到这个标志位并停止执行。
3. 不推荐使用的 stop()
方法
stop()
方法是 Java 早期提供的用于停止线程的方法,但由于它会强制终止线程,可能会导致线程持有的锁被突然释放,从而引发数据不一致等问题,因此不推荐使用。
以下是使用 stop()
方法停止线程的示例代码:
class MyThread extends Thread {
@Override
public void run() {
while (true) {
// 线程执行的任务
System.out.println("线程正在执行...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class StopThreadByStop {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
try {
// 线程执行 5 秒后停止
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 不推荐使用的方法
thread.stop();
}
}
虽然 stop()
方法可以停止线程,但由于其存在的问题,不建议在实际开发中使用。
综上所述,推荐使用标志位或 interrupt()
方法来停止线程,以保证线程的安全和数据的一致性。