interrupt
一个检查isinterrupted的程序
package concurrent._interrupt; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class Demo2 { private static int c = 0 ; public static void main(String[] args) { List<BigInteger> list = new ArrayList<BigInteger>(); ThreadB threadB = new ThreadB(list); threadB.start(); System.out.println("Main方法开始睡眠1000 ms"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Main准备中断子线程"); threadB.interrupt(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("list的size" + list.size()); } } class ThreadB extends Thread { private List<BigInteger> list ; public ThreadB(List list){ super("ThreadB"); this.list = list; } @Override public void run() { String threadName = this.getName(); System.out.println(threadName + "已经启动了"); myInter(); System.out.println(threadName + "已经结束了"); } private void myInter() { BigInteger bigInteger =BigInteger.ONE; //死循环,轮询中断条件 for(;!this.isInterrupted();){ this.list.add(bigInteger.nextProbablePrime()); } System.out.println("结束myInter"); } }
结果:
Main方法开始睡眠1000 ms
ThreadB已经启动了
Main准备中断子线程
结束myInter
ThreadB已经结束了
list的size70091071