如何正确的停止一个线程
通常定义一个标记,来判断标记的状态停止线程的执行
package gov.mof.fasp2.gcfr.adjustoffset.adjust; public class Main { public static void main(String[] args) { //Runnable r1 = new Processor(); Processor r1 = new Processor(); Thread t1 = new Thread(r1, "t1"); t1.start(); try { Thread.sleep(20); }catch(Exception e) {} //停止线程 r1.setFlag(true);
System.out.println("mainEnd"); } } class Processor implements Runnable { //线程停止标记,true为停止 private boolean flag; public void run() { for (int i=1; i<100; i++) { System.out.println(Thread.currentThread().getName() + "," + i); //为true停止线程执行 if (flag) { break; } } } public void setFlag(boolean flag) { this.flag = flag; } }
主线程结束时停止t1线程