java 停止线程
时间: 2023-11-21 19:57:02 浏览: 39
Java中停止线程的方法有多种,具体方法取决于线程的执行状态。以下是一些常见的方法:
1. 使用interrupt()方法停止线程:在run()方法中使用isInterrupted()方法检查线程是否被中断,如果被中断则停止线程。例如:
```java
public class MyThread extends Thread {
public void run() {
while (!isInterrupted()) {
// 线程执行的代码
}
}
}
// 停止线程的代码
MyThread thread = new MyThread();
thread.start();
thread.interrupt();
```
2. 使用标志位停止线程:在run()方法中使用一个标志位来控制线程的执行状态,当标志位为false时停止线程。例如:
```java
public class MyThread extends Thread {
private volatile boolean flag = true;
public void run() {
while (flag) {
// 线程执行的代码
}
}
public void stopThread() {
flag = false;
}
}
// 停止线程的代码
MyThread thread = new MyThread();
thread.start();
thread.stopThread();
```
3. 使用Thread.stop()方法停止线程(不建议使用):Thread.stop()方法可以直接停止线程,但是这种方法不建议使用,因为它会导致线程的状态不一致。例如:
```java
public class MyThread extends Thread {
public void run() {
while (true) {
// 线程执行的代码
}
}
}
// 停止线程的代码
MyThread thread = new MyThread();
thread.start();
thread.stop();
```