| 
                         线程运行状态时 Thread.isInterrupted() 返回的线程状态是 false,然后调用 thread.interrupt() 中断线程  Thread.isInterrupted() 返回的线程状态是 true,最后调用 Thread.interrupted()  复位线程Thread.isInterrupted() 返回的线程状态是 false 或者抛出 InterruptedException  异常之前,线程会将状态设为 false。 
下面来看下两种方式复位线程的代码,首先是 Thread.interrupted() 的方式复位代码: 
- public class InterruptDemo { 
 -  
 -     public static void main(String[] args) throws InterruptedException { 
 -         Thread thread = new Thread(() -> { 
 -             while (true) { 
 -                 //Thread.currentThread().isInterrupted()默认是false,当main方式执行thread.interrupt()时,状态改为true 
 -                 if (Thread.currentThread().isInterrupted()) { 
 -                     System.out.println("before:" + Thread.currentThread().isInterrupted());//before:true 
 -                     Thread.interrupted(); // 对线程进行复位,由 true 变成 false 
 -                     System.out.println("after:" + Thread.currentThread().isInterrupted());//after:false 
 -                 } 
 -             } 
 -         }, "interruptDemo"); 
 -         thread.start(); 
 -         TimeUnit.SECONDS.sleep(1); 
 -         thread.interrupt(); 
 -     } 
 - } 
 
  
抛出 InterruptedException 复位线程代码: 
- public class InterruptedExceptionDemo { 
 -  
 -     public static void main(String[] args) throws InterruptedException { 
 -         Thread thread = new Thread(() -> { 
 -             while (!Thread.currentThread().isInterrupted()) { 
 -                 try { 
 -                     TimeUnit.SECONDS.sleep(1); 
 -                 } catch (InterruptedException e) { 
 -                     e.printStackTrace(); 
 -                     // break; 
 -                 } 
 -             } 
 -         }, "interruptDemo"); 
 -         thread.start(); 
 -         TimeUnit.SECONDS.sleep(1); 
 -         thread.interrupt(); 
 -         System.out.println(thread.isInterrupted()); 
 -     } 
 - } 
 
                          (编辑:91站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |