1.5 线程停止
结束线程有以下三种方法:
(1)设置退出标志,使线程正常退出。
(2)使用interrupt()方法中断线程。
(3)使用stop方法强行终止线程(不推荐使用Thread.stop, 这种终止线程运行的方法已经被废弃,使用它们是极端不安全的!)
public class Demo8Exit { public static boolean exit = true; public static void main(String[] args) throws InterruptedException { Thread t = new Thread(new Runnable() { public void run() { while (exit) { try { System.out.println("线程执行!"); Thread.sleep(100l); } catch (InterruptedException e) { e.printStackTrace(); } } } }); t.start(); Thread.sleep(1000l); exit = false; System.out.println("退出标识位设置成功"); } }
public class Demo9Interrupt { public static boolean exit = true; public static void main(String[] args) throws InterruptedException { Thread t = new Thread(new Runnable() { public void run() { while (exit) { try { System.out.println("线程执行!"); //判断线程的中断标志来退出循环 if (Thread.currentThread().isInterrupted()) { break; } Thread.sleep(100l); } catch (InterruptedException e) { e.printStackTrace(); //线程处于阻塞状态,当调用线程的interrupt()方法时, //会抛出InterruptException异常,跳出循环 break; } } } }); t.start(); Thread.sleep(1000l); //中断线程 t.interrupt(); System.out.println("线程中断了"); } }