【Java并发编程学习】2、线程中断

public class SleepInterrupt extends Object implements Runnable {
    @Override
    public void run() {
        System.out.println("in run() - enter normally");
        try {
            System.out.println("in run() - about to sleep for 20 seconds");
            Thread.sleep(20000);
            System.out.println("in run() - woke up");
        } catch (InterruptedException e) {
            System.out.println("in run() - interrupted while sleeping");
            /**
             * 处理完中断异常后,返回run()方法入口,
             * 如果没有return,线程不会实际被中断,它会继续打印下面的信息
             */
            return;
        }
        System.out.println("in run() - leaving normally");
    }
}
public class InterruptDemo {
    public static void main(String[] args) {
        SleepInterrupt sleepInterrupt = new SleepInterrupt();
        Thread thread = new Thread(sleepInterrupt);
        thread.start();
        // 主线程休眠2秒,从而确保刚才启动的线程有机会执行一段时间
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("in main() - interrupting other thread");
        /**
         * 当一个线程运行时,另一个线程可以调用对应的Thread对象的interrupt()方法来中断它,
         * 该方法只是在目标线程中设置一个标志,表示它已经被中断,并立即返回
         */
        thread.interrupt();
        System.out.println("in main() - leaving");
    }
}

猜你喜欢

转载自my.oschina.net/u/3545495/blog/1809550
今日推荐