在 java 中间结束线程的三种方法是:使用 stop() 方法(不再推荐);使用 interrupt() 该方法发送中断信号;使用 join() 方法允许主线程等待目标线程完成。

Java 结束线程的三种方法
在 Java 有很多方法可以结束线程。以下是三种最常用的方法:
1. 使用 stop() 方法
注意:stop() 不再推荐使用该方法,因为它可以直接终止线程,并可能导致数据损坏或其他问题。
<code class="java">public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
// 线程任务
});
thread.start();
thread.stop();
}
}</code>登录后复制
2. 使用 interrupt() 方法
interrupt() 该方法可以通过检查向线程发送中断信号 Thread.interrupted() 确定是否已收到中断信号。
<code class="java">public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
while (!Thread.interrupted()) {
// 线程任务
}
});
thread.start();
thread.interrupt();
}
}</code>登录后复制
3. 使用 join() 方法
join() 该方法允许主线程等待目标线程完成执行。主线程将在目标线程完成后继续执行。
<code class="java">public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
// 线程任务
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}</code>登录后复制
以上是java结束线程三种方法的详细内容。请关注图灵教育的其他相关文章!