yu766588220
花公子丶
2016-08-12 08:29

关于Java线程的isInterrupted方法问题

3

我调用interrupt方法中断线程后,isInterrupted仍然为false。看代码第二个注释处

 public class InterruptThread
{
    public static void main(String[] args) {

        Mythread mythread= new Mythread();
        mythread.start();
        try {
            Thread.sleep(10000);//主线程休眠十秒,让子线程执行十秒,然后中断mythread子线程
            mythread.interrupt();
            Thread.sleep(3000);
            //明明调用了mythread.interrupt(),下面这句却还是false,这是为何?
            System.out.println("线程是否已经中断:"+mythread.isInterrupted());
            System.out.println("线程是否已经中断:"+mythread.interrupted());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
class Mythread extends Thread{
    @Override
    public void run(){
        try {
            while(true){
                interruptableMethod();
            }
        } 
        catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName()+"线程中断了");
        }
    }

    public void interruptableMethod() throws InterruptedException{
        System.out.println("方法开始执行");
        sleep(2000);
        System.out.println("方法结束");
    }
}

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

3条回答

为你推荐