设为首页 加入收藏

TOP

Java应用线程泄漏原因分析与避免(四)
2017-03-30 14:17:53 】 浏览:466
Tags:Java 应用 线程 泄漏 原因分析 避免
一个变量里,例如t,然后通过t去停止这个线程。停止线程的方法一般有stop,destroy,interrupt等,但是stop,destroy都已经被废弃了,因为可能造成死锁,所以通常等做法是使用interrupt。使用interrupt其实类似于信号,就好比你在Linux进程中把SIGTERM信号忽略了,那就没法通过kill杀死进程了,interrupt也是如此。 下面等线程只会报一个异常,中断信号被忽略。


public static void main(String[] args) {
    Thread t = new Thread(new Runnable() {
    @Override
    public void run() {
        while(true) {
        try {
            Thread.sleep(1000);
            System.out.println("wake up");
            } catch(InterruptedException e) {
            e.printStackTrace();
            }
        }
    }
    });
    t.start();
    t.interrupt();//并不能停止线程
}


这种阻塞的线程,一般调用的函数都会强制检查并抛出interruption异常,类似的还有wait(),阻塞队列的take等,为了程序能正常关闭,InterruptedException最好不好忽略。


public static void main(String[] args) {
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                    System.out.println("wake up");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.out.println("stop...");
                    break;
                }
            }
        }
    });
    t.start();
    t.interrupt();
}


如果run方法里没有抛出InterruptedException怎么办?例如下面这个


 public static void main(String[] args) {
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            int i = 0;
            while (true) {
                i++;
            }
        }
    });
    t.start();
    t.interrupt();
}


这种情况就需要run方法里不断检查是否被中断了,否则永远停不下来。


 public static void main(String[] args) {
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            int i = 0;
            while (true) {
                i++;
                if(Thread.interrupted()) {
                    System.out.println("stop..");
                    break;
                }
            }
        }
    });
  &n

首页 上一页 1 2 3 4 下一页 尾页 4/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇对Spring Web启动时IOC源码研究 下一篇Java中volatile关键字的含义

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目