zoukankan      html  css  js  c++  java
  • 线程中断

    线程中断:

    public static boolean interrupted 测试当前线程是否已经中断。线程的中断状态 由该方法清除。换句话说,如果连续两次调用该方法,则第二次调用将返回 false(在第一次调用已清除了其中断状态之后,且第二次调用检验完中断状态前,当前线程再次中断的情况除外)。
    public boolean isInterrupted() 测试线程是否已经中断。线程的中断状态 不受该方法的影响。
    public void interrupt() 标记中断标记

    Java的中断是一种协作机制,在线程调用interrupt()方法的时候虚拟机会在此线程上标记一个标志(这个中断标志只是一个布尔类型的变量),代表这个线程可能被中断,在后面的中断操作也是根据这个中断标志执行的。

    如果一个线程处于了阻塞状态(如线程调用了sleep()、join()、wait()、以及可中断的通道上的 I/O 操作方法后可进入阻塞状态),则在线程在检查中断标示时如果发现中断标示为true,则会在这些阻塞方法(sleep()、join()、wait()及可中断的通道上的 I/O 操作方法)调用处抛出InterruptedException异常,并且在抛出异常后立即将线程的中断标示位清除,即重新设置为false。
     例子:

     1 public class ThreadImterrupt {
     2     public static void main(String[] args){
     3         Thread t1 =new Thread(){ 
     4             public void run(){
     5                 try {
     6                     Thread.sleep(1000000);
     7                 } catch (InterruptedException e) {
     8                     // TODO Auto-generated catch block
     9                     e.printStackTrace();
    10                 }
    11                 for(int i=0; i<10; i++){
    12                     System.out.println("Sleep");
    13                 }
    14             }
    15         };
    16         
    17          
    18         t1.start();
    19         t1.interrupt();
    20         System.out.println(t1.isInterrupted());
    21         System.out.println(Thread.interrupted());
    22     }
    23 }

    结果:

     1 true
     2 false
     3 Sleep
     4 Sleep
     5 Sleep
     6 Sleep
     7 Sleep
     8 Sleep
     9 Sleep
    10 Sleep
    11 Sleep
    12 Sleep
    13 java.lang.InterruptedException: sleep interrupted
    14     at java.lang.Thread.sleep(Native Method)
    15     at test.ThreadImterrupt$1.run(ThreadImterrupt.java:8)
  • 相关阅读:
    CS229 6.4 Neurons Networks Autoencoders and Sparsity
    CS229 6.3 Neurons Networks Gradient Checking
    【Leetcode】【Easy】Min Stack
    【Leetcode】【Easy】Merge Sorted Array
    【Leetcode】【Easy】ZigZag Conversion
    【Leetcode】【Easy】Valid Palindrome
    【Leetcode】【Easy】Reverse Integer
    【Leetcode】【Easy】Palindrome Number
    【Leetcode】【Easy】Length of Last Word
    【Leetcode】【Easy】Remove Nth Node From End of List
  • 原文地址:https://www.cnblogs.com/feichangnice/p/10648764.html
Copyright © 2011-2022 走看看