java在sleep时调用interrupt方法

来源:互联网 发布:淘宝店铺手机能激活吗 编辑:程序博客网 时间:2024/04/29 23:49
 sleep() & interrupt()
线程A正在使用sleep()暂停着: Thread.sleep(100000);
如果要取消他的等待状态,可以在正在执行的线程里(比如这里是B)调用
    a.interrupt();
令线程A放弃睡眠操作,这里a是线程A对应到的Thread实例

执行interrupt()时,并不需要获取Thread实例的锁定.任何线程在任何时刻,都可以调用其他线程interrupt().当sleep中的线程被调用interrupt()时,就会放弃暂停的状态.并抛出InterruptedException.丢出异常的,是A线程.

情况1:先睡眠后打断,则直接打断睡眠,并且清除停止状态值,使之变成false:

public class MyThread extends Thread{    @Override    public void run() {        super.run();        try{            System.out.println("run begin");            Thread.sleep(200000);            System.out.println("run end");        }catch (InterruptedException e){            System.out.println("在沉睡中被停止!进入catch!"+this.isInterrupted());            e.printStackTrace();        }    }}
public class Run {    public static void main(String[] args){        try{            MyThread thread=new MyThread();            thread.start();            Thread.sleep(200);            thread.interrupt();        }catch (InterruptedException e){            System.out.println("main catch");            e.printStackTrace();        }        System.out.println("end!");    }}
run begin
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.mr.three.MyThread.run(MyThread.java:12)
end!
在沉睡中被停止!进入catch!false

情况2:先打断后睡眠,则直接不睡眠:

public class MyThread extends Thread{    @Override    public void run() {        super.run();        try{            System.out.println("run begin");            for(int i=0;i<500000;i++){                System.out.println(i);            }            Thread.sleep(200000);            System.out.println("run end");        }catch (InterruptedException e){            System.out.println("在沉睡中被停止!进入catch!"+this.isInterrupted());            e.printStackTrace();        }    }}
public class Run {    public static void main(String[] args){        try{            MyThread thread=new MyThread();            thread.start();            Thread.sleep(1);            thread.interrupt();        }catch (InterruptedException e){            System.out.println("main catch");            e.printStackTrace();        }        System.out.println("end!");    }}
499997
499998
499999
在沉睡中被停止!进入catch!false
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.mr.three.MyThread.run(MyThread.java:15)

阅读全文
0 0
原创粉丝点击