测试如下
1 package com.cky.thread; 2 3 /** 4 * Created by edison on 2017/12/3. 5 */ 6 public class MyThread12 extends Thread{ 7 @Override 8 public void run() { 9 super.run(); 10 for (int i = 0; i < 50000; i++) { 11 if (Thread.interrupted()) { 12 System.out.println("子线程已经停止了,我要退出"); 13 break; 14 } 15 System.out.println("i="+(i+1)); 16 } 17 System.out.println("for循环后继续执行"); 18 } 19 }
1 package com.cky.test; 2 3 import com.cky.thread.MyThread12; 4 5 /** 6 * Created by edison on 2017/11/27. 7 */ 8 public class Test1 { 9 public static void main(String[] args) { 10 11 try { 12 MyThread12 th = new MyThread12(); 13 th.start(); 14 Thread.sleep(20); 15 th.interrupt(); 16 } catch (InterruptedException e) { 17 System.out.println("main catch"); 18 e.printStackTrace(); 19 } 20 System.out.println("main end"); 21 22 23 } 24 }
1 i=1229 2 i=1230 3 i=1231 4 i=1232 5 i=1233 6 i=1234 7 子线程已经停止了,我要退出 8 for循环后继续执行 9 main end
结果分析,这时cpu切换到了主线程执行了interrupt函数,这时,再进入for循环,前面已经执行到了1234,这时打完标记的子线程已经中断了,这时break跳出当前的for循环,但是下面的for循环外的语句还是
会执行的,因为线程已经打了标记,但是线程并没有被立刻中断
那如何使线程被立刻中断呢?
可以用抛出异常的方法
1 package com.cky.test; 2 3 import com.cky.thread.MyThread12; 4 5 /** 6 * Created by edison on 2017/11/27. 7 */ 8 public class Test1 { 9 public static void main(String[] args) { 10 11 try { 12 MyThread12 th = new MyThread12(); 13 th.start(); 14 Thread.sleep(20); 15 th.interrupt(); 16 } catch (InterruptedException e) { 17 System.out.println("main catch"); 18 e.printStackTrace(); 19 } 20 System.out.println("main end"); 21 22 23 } 24 }
1 package com.cky.thread; 2 3 /** 4 * Created by edison on 2017/12/3. 5 */ 6 public class MyThread12 extends Thread{ 7 @Override 8 public void run() { 9 super.run(); 10 try { 11 for (int i = 0; i < 50000; i++) { 12 if (Thread.interrupted()) { 13 System.out.println("子线程已经停止了,我要退出"); 14 throw new InterruptedException(); 15 } 16 System.out.println("i="+(i+1)); 17 } 18 System.out.println("for循环后继续执行"); 19 } catch (InterruptedException e) { 20 System.out.println("进run方法的catch了"); 21 e.printStackTrace(); 22 } 23 } 24 }
1 i=1293 2 i=1294 3 i=1295 4 i=1296 5 子线程已经停止了,我要退出 6 进run方法的catch了 7 main end 8 java.lang.InterruptedException 9 at com.cky.thread.MyThread12.run(MyThread12.java:14)
时间: 2024-11-01 22:26:12