最常用就是让线程的run方法结束,无论是return结束,还是抛异常结束,都可以。
stop方法---不推荐使用
@Deprecated public final void stop() {
使用共享变量---很少使用
通过修改共享变量的值,让线程循环结束,结束run方法
public class StopThreadTest { static volatile boolean flag = true; public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(() -> { while (flag) { System.out.println("任務正在執行"); } System.out.println("任務結束"); }); t1.start(); Thread.sleep(500); flag = false; } }
interrupt方式---推荐使用
public static void main(String[] args) throws InterruptedException { // Interrupt标记,默认false System.out.println(Thread.currentThread().isInterrupted()); // Interrupt Thread.currentThread().interrupt(); // 查询标记状态 System.out.println(Thread.currentThread().isInterrupted()); // 返回当前线程标记状态,且复位Interrupt标记状态 System.out.println(Thread.interrupted()); Thread t1 = new Thread(()-> { while (!Thread.currentThread().isInterrupted()) { System.out.println("线程正在执行"); } System.out.println("线程执行结束"); }); t1.start(); Thread.sleep(500); t1.interrupt(); }