packagecom.ysf.day0427;publicclassTst03ShareVar{staticvolatileboolean flag =true;publicstaticvoidmain(String[] args)throwsInterruptedException{Thread t =newThread(()->{while(flag){//处理业务}System.out.println("任务结束");},"share-1");
t.start();Thread.sleep(1000L);
flag =false;}}
3.使用interrupt
3.1 interrupt标记位
线程中存在一个标记位interrupt,来标识线程是否被打断
该标记位默认情况下是false
3.2 查询线程标记位
对象方法:isInterrupted()
packagecom.ysf.day0427;publicclassTst04QueryInterrupt{publicstaticvoidmain(String[] args)throwsInterruptedException{Thread t1 =newThread(()->{for(int i =0;i<5;i++){System.out.println(i);try{Thread.sleep(500L);}catch(InterruptedException e){
e.printStackTrace();}}},"interrupt-1");
t1.start();Thread.sleep(1000L);System.out.println(t1.isInterrupted());}}