【问题标题】:Thread termination using interrupt method使用中断方法终止线程
【发布时间】:2017-01-27 16:01:37
【问题描述】:

我有一个运行文件解析任务的线程。它设置为一个守护线程,从tomcat启动到关闭执行其任务在后台运行。

我希望在中断和服务器关闭时处理线程终止。我想知道我的操作是否正确。

class LoadingModule{             // Thread is started from here
    threadsStartMethod() {
        Thread t = new Thread(FileParseTask);
        t.setDaemon(true);
        t.start();
    }
}

Class FileParseTask implements Runnable {

    @Override
    public void run() {
        try {
            while(!Thread.currentThread.isInterrupted) {
                // poll for file creation
                // parse and store
            }
        } catch(Exception exit) {
            log.error(message);
            Thread.currentThread.interrupt();
        }
    }
}

这会在所有情况下都干净地退出线程吗?

【问题讨论】:

    标签: java multithreading tomcat thread-safety interrupted-exception


    【解决方案1】:

    这取决于循环内的代码。如果循环内的代码捕获到中断的异常并恢复,你将永远看不到它。通用异常“退出”也隐藏了其他异常。更改代码,让您知道发生了什么。

    我会做以下事情

    Class FileParseTask implements Runnable {
    
        @Override
        public void run() {
    
                while(!Thread.currentThread.isInterrupted) {
                    try {
                    // poll for file creation
                    // parse and store
                    } catch(Exception exit) {
                        if (InterruptedException)
                             break;
                        else{
                          //
                        }
                        log.error(message);
                    }
                }
        }
    }
    

    这对我有用,最多 2K 线程没有问题

    【讨论】:

    • 我是否需要在 catch 块中调用 Thread.CurrentThread.interrupt() 才能将中断标志设置为 true ?或者 while(!Thread.CurrentThread.isinInterrupted) 在某些中断时会自动将值设为 true 吗?
    • 可能不会。如果您在 if (instanceof Interruptedexception) 块内,我认为您有足够的信息可以跳出循环。如果需要,您还可以检查当前线程的状态
    • 为什么从catch stackoverflow.com/questions/4906799/…调用interrupt()
    • 这就是为什么我说可能不是。在我的情况下,不需要广播状态,因为没有其他人对中断感兴趣。在您的情况下,这可能是有意义的,因为您没有使用任何关闭挂钩。设置正确的状态并没有什么坏处
    猜你喜欢
    • 2015-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多