跳转到主内容
新派编程网 - 新潮编程理念,全新技术课堂!

java结束线程的三种方法

在 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(); } } }

相关文章