码迷,mamicode.com
首页 > 其他好文 > 详细

四、interrupt()

时间:2016-06-27 06:45:25      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

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("未中断");
        }
    }
}

 

四、interrupt()

标签:

原文地址:http://www.cnblogs.com/futiansu/p/5619030.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!