在 Java 中结束线程的三种方法分别是:使用 stop() 方法(已不再建议使用);使用 interrupt() 方法发送中断信号;使用 join() 方法让主线程等待目标线程完成。
Java 结束线程的三种方法
在 Java 中,有多种方法可以结束线程。以下介绍三种最常用的方法:
1. 使用 stop() 方法
注意:stop() 方法已不再建议使用,因为它会直接终止线程,可能导致数据损坏或其他问题。
立即学习“Java免费学习笔记(深入)”;
public class Main { public static void main(String[] args) { Thread thread = new Thread(() -> { // 线程任务 }); thread.start(); thread.stop(); } }
2. 使用 interrupt() 方法
interrupt() 方法会向线程发送一个中断信号,线程可以通过检查 Thread.interrupted() 来确定是否已经收到中断信号。
public class Main { public static void main(String[] args) { Thread thread = new Thread(() -> { while (!Thread.interrupted()) { // 线程任务 } }); thread.start(); thread.interrupt(); } }
3. 使用 join() 方法
join() 方法会让主线程等待目标线程完成执行。当目标线程完成后,主线程才会继续执行。
public class Main { public static void main(String[] args) { Thread thread = new Thread(() -> { // 线程任务 }); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } }
以上就是java结束线程的三种方法的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号