退出线程主要的思路是用一个标志位或者是使用线程的中断方法
下面的例子是可以确保调用shutdown()方法,无论线程是否在休眠中,线程都会退出
public class ThreadTest extends Thread { private volatile boolean exit = false; @Override public void run() { while (!exit) { try { System.out.println("######"); Thread.sleep(10000); //休眠中了,shutdown(),会结束线程 System.out.println("^^^^^^^^^"); //正在执行这行代码时,shutdown(),exit被修改为true了,退出循环了,线程结束 } catch (InterruptedException e) { exit = true; e.printStackTrace(); break; } } } public void shutdown() { exit = true; this.interrupt(); } public static void main(String[] args) throws InterruptedException { ThreadTest thread = new ThreadTest(); thread.start(); Thread.sleep(3000); thread.shutdown(); } }