设为首页 加入收藏

TOP

Java线程的中断(二)
2019-09-03 03:40:10 】 浏览:135
Tags:Java 线程 中断
d().getName() + "睡了5秒");
        } catch (Exception e) {
            System.out.println(Thread.currentThread().getName() + "runnable exception:" + e);
        } finally {
            lock.unlock();
        }
        System.out.println(Thread.currentThread().getName() + " over");
    }
}


执行结果为:


main start
Thread-0runnable run
Thread-0开始睡眠
main end
Thread-1runnable run
Thread-0睡了5秒
Thread-0 over
Thread-1开始睡眠
Thread-1runnable exception:java.lang.InterruptedException: sleep interrupted
Thread-1 over


可以看到中断了并没有对获取锁产生影响,最后是sleep方法响应的中断。


下面是我在本地模拟的lockInterruptibly()阻塞中断:


public class ReentrantLockInterruptableDemo {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("main start");
        Thread thread1 = new Thread(new LockThreadInterruptableDemo());
        Thread thread2 = new Thread(new LockThreadInterruptableDemo());
        thread1.start();
        Thread.sleep(1000); // 确保thread1获取到了锁
        thread2.start(); // 此时thread2处于获取锁的阻塞状态
        thread2.interrupt();
        System.out.println("main end");
    }
}


class LockThreadInterruptableDemo implements Runnable {
    public static ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "runnable run");
        try {
            lock.lockInterruptibly();
            System.out.println(Thread.currentThread().getName() + "开始睡眠");
            Thread.sleep(5000);
            System.out.println(Thread.currentThread().getName() + "睡了5秒");
        } catch (Exception e) {
            System.out.println(Thread.currentThread().getName() + "runnable exception:" + e);
        } finally {
            try {
                lock.unlock();
            } catch (IllegalMonitorStateException e) {
                System.out.println("因线程" + Thread.currentThread().getName() + "提前中断导致未获取到锁");
            }
        }
        System.out.println(Thread.currentThread().getName() + " over");
    }
}


结果为:


main start
Thread-0runnable run
Thread-0开始睡眠
main end
Thread-1runnable run
Thread-1runnable exception:java.lang.InterruptedException
因线程Thread-1提前中断导致未获取到锁
Thread-1 over
Thread-0睡了5秒
Thread-0 over


结束语


对于线程中断的处理比较常见,尤其是涉及到多线程的框架、组件中。而能否处理好线程中断的各种情况,则体现出一个程序员对多线程掌握的熟练情况。


首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Thread线程的基础知识及常见疑惑点 下一篇算法之常见排序算法-冒泡排序、归..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目