1 /** 2 * 线程外部终止(提供标志位用于终止线程) 3 */ 4 public class ThreadStop implements Runnable{ 5 private boolean flag = true; 6 private int a = 0; 7 8 @Override 9 public void run() { 10 while(flag) { 11 System.out.println("正在运行:" + a++); 12 } 13 } 14 15 public void checkThread() { //提供给外部的终止方法 16 this.flag = false; 17 } 18 19 public static void main(String[] args) { 20 ThreadStop threadStop = new ThreadStop(); 21 new Thread(threadStop).start(); 22 for(int a = 0;a<99;a++) { 23 System.out.println("main"+a); 24 if(a == 50) { //线程终止条件 25 System.out.println("main"+a); 26 threadStop.checkThread(); 27 System.out.println("线程终止"); 28 } 29 } 30 } 31 }
原文:https://www.cnblogs.com/zhang741741/p/13263523.html