/** * 设置标识位停止线程 */ public class MyThreadStop { //计数 private static int count = 0; //退出标识符 public static boolean exit = false; /** * 核心线程 */ public static void main(final String[] arguments) throws InterruptedException { Thread t = new Thread(new TestThread()); t.start(); } /** * 同步方法 */ public static synchronized void countNum() { for (int i = 0; i < 100000; i++) { if (count >= 500000) { exit = true; //修改标志位,退出线程 } else { count++; System.out.println(count); } } } /** * 线程实体(实现Runnable接口) */ static class TestThread implements Runnable { public void run() { while (!exit) {//当标识符没设置停止时,一直做参数递增 countNum(); } } } }
/** * interrupt()方法停止线程 */ public class MyThreadStop { //计数器 private static int count = 0; /** * 核心线程 */ public static void main(final String[] arguments) throws InterruptedException { Thread t = new Thread(new TestThread()); t.start(); //休眠一会儿,然后中断 t.sleep(200); t.interrupt(); } /** * 同步方法 */ public static synchronized void countNum() { for (int i = 0; i < 500000; i++) { count++; System.out.println(count); } } /** * 线程实体(实现Runnable接口) */ static class TestThread implements Runnable { public void run() { countNum(); } } }

上面的例子我们发现,好像interrupt方法并没有马上停止线程,还是继续跑完了,这是由于interrupt() 方法仅仅是在当前线程中打一个停止的标记,并不会立即终止线程。 至于目标线程收到通知后会如何处理,则完全由目标线程自行决定。
我们可以改造一下~
/** * interrupt()方法停止线程 */ public class MyThreadStop { //计数器 private static int count = 0; /** * 核心线程 */ public static void main(final String[] arguments) throws InterruptedException { Thread t = new Thread(new TestThread()); t.start(); //休眠一会儿,然后中断 t.sleep(200); t.interrupt(); } /** * 线程实体(实现Runnable接口) */ static class TestThread implements Runnable { public void run() { for (int i = 0; i < 500000; i++) { //判断线程是否被通知中断 if (Thread.currentThread().isInterrupted()) { //处理中断逻辑 break; } count++; System.out.println(count); } } } }

可以发现,在加入中断判断以后,线程停止了工作
PS:当线程被 sleep() 休眠时,如果被中断,就会抛出一个 InterruptedException异常。
PS:Thread.sleep() 方法由于中断而抛出的异常,是会清除中断标记的,线程后面的代码会继续执行。
stop()方法停止线程的方式相当粗暴,直接停止线程工作,相当不安全,虽然现在已经弃用,还是简单的了解一下吧。
为什么弃用stop:
好文推荐:
原文:https://www.cnblogs.com/riches/p/12023692.html