打字猴:1.700449939e+09
1700449939
1700449940 public void run(){
1700449941
1700449942 //线程一直运行
1700449943
1700449944 while(true){
1700449945
1700449946 System.out.println(“Running……”);
1700449947
1700449948 }
1700449949
1700449950 }
1700449951
1700449952 };
1700449953
1700449954 //启动t1线程
1700449955
1700449956 t1.start();
1700449957
1700449958 //中断t1线程
1700449959
1700449960 t1.interrupt();
1700449961
1700449962 }
1700449963
1700449964 执行这段代码,你会发现一直有Running在输出,永远不会停止,似乎执行了interrupt没有任何变化,那是因为interrupt方法不能终止一个线程状态,它只会改变中断标志位(如果在t1.interrupt()前后输出t1.isInterrupted()则会发现分别输出了false和true),如果需要终止该线程,还需要自行进行判断,例如我们可以使用interrupt编写出更加简洁、安全的终止线程代码:
1700449965
1700449966 class SafeStopThread extends Thread{
1700449967
1700449968 @Override
1700449969
1700449970 public void run(){
1700449971
1700449972 //判断线程体是否运行
1700449973
1700449974 while(!isInterrupted()){
1700449975
1700449976 //Do Something
1700449977
1700449978 }
1700449979
1700449980 }
1700449981
1700449982 }
1700449983
1700449984 总之,如果期望终止一个正在运行的线程,则不能使用已经过时的stop方法,需要自行编码实现,如此即可保证原子逻辑不被破坏,代码逻辑不会出现异常。当然,如果我们使用的是线程池(比如ThreadPoolExecutor类),那么可以通过shutdown方法逐步关闭池中的线程,它采用的是比较温和、安全的关闭线程方法,完全不会产生类似stop方法的弊端。
1700449985
1700449986
1700449987
1700449988
[ 上一页 ]  [ :1.700449939e+09 ]  [ 下一页 ]