即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

线程interrupt办法

编程语言 afan249 33℃ 0评论

interrupt不可以中断一个正在运行的线程,但是她可以中断阻塞的线程

public class Interrupted {

    public static void main(String[] args) {
        //sleepthread 不停的常设睡眠
        Thread sleepThread = new Thread(new SleepRunner(),"sleepthread");
        sleepThread.setDaemon(true);
        //busythread不停的运行
        Thread busyThread = new Thread(new BusyRunner(),"busyThread");
        busyThread.setDaemon(true);
        sleepThread.start();
        busyThread.start();

        //休眠5秒  让sleepThread和busythread充分运行
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        sleepThread.interrupt();
        busyThread.interrupt();

        System.out.println("sleepThread interrupted is " + sleepThread.isInterrupted());
        System.out.println("busyThread interrupted is " + busyThread.isInterrupted());

        while(true){
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    static class SleepRunner implements Runnable{
        @Override
        public void run() {
            while(true){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    static class BusyRunner implements Runnable{
        @Override
        public void run() {
            while(true){
                System.out.println("qqqqqqqqqqqq");
            }
        }
    }
}

转载请注明:CodingBlog » 线程interrupt办法

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情