zoukankan      html  css  js  c++  java
  • 四、interrupt()

    interrupt()的作用是中断本线程。
    本线程中断自己是被允许的;其它线程调用本线程的interrupt()方法时,会通过checkAccess()检查权限。这有可能抛出SecurityException异常。
    如果本线程是处于阻塞状态:调用线程的wait(), wait(long)或wait(long, int)会让它进入等待(阻塞)状态,或者调用线程的join(), join(long), join(long, int), sleep(long), sleep(long, int)也会让它进入阻塞状态。若线程在阻塞状态时,调用了它的interrupt()方法,那么它的“中断状态”会被清除并且会收到一个InterruptedException异常。例如,线程通过wait()进入阻塞状态,此时通过interrupt()中断该线程;调用interrupt()会立即将线程的中断标记设为“true”,但是由于线程处于阻塞状态,所以该“中断标记”会立即被清除为“false”,同时,会产生一个InterruptedException的异常。
    如果线程被阻塞在一个Selector选择器中,那么通过interrupt()中断它时;线程的中断标记会被设置为true,并且它会立即从选择操作中返回。
    如果不属于前面所说的情况,那么通过interrupt()中断线程时,它的中断标记会被设置为“true”。
    中断一个“已终止的线程”不会产生任何操作。   

    上面网络上给出的解释。

    个人理解:interrupt()的作用是中断本线程。当一个线程对象调用interrupt()方法时,会有一个中断标记。如果接下来线程有调用join(),sleep(long),wait()等方法就将抛出InterruptedException异常。如果处于运行状态,那么可以通过调用isInterrupted()来判断是否有中断标记,然后进行下一步操作。

    package com.fla.thread;
    
    
    public class InterruptTest {
        
        
        
        public static void main(String[] args) {
            final A a = new A();
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    a.getB();
                }
            });
            thread.start();
            thread.interrupt();
        }
        
        
    }
    class A {
        boolean flag=true ;
        
        public synchronized void getA(){
            while(flag){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    System.out.println("中断了");
                    break;
                }
            }
            System.out.println("xixi");
            flag = false;
        }
        
        public void getB(){
            for(int i = 0;i<100;i++){
                if((i%10)==0)   //消耗点时间
                    System.out.println(i);
            }
            if(Thread.currentThread().isInterrupted()){
                System.out.println("中断");
            }else {
                System.out.println("未中断");
            }
        }
    }
  • 相关阅读:
    数据库连接池、事务
    JDBC、单元测试、DAO模式
    归并排序
    插入排序
    MySQL数据库
    JQuery
    JavaScript
    算法训练 连续正整数的和
    算法提高 寻找三位数
    算法训练 学做菜
  • 原文地址:https://www.cnblogs.com/futiansu/p/5619030.html
Copyright © 2011-2022 走看看