如何知道线程何时停止或停止? [英] How to know when a thread stops or is stopped?

查看:120
本文介绍了如何知道线程何时停止或停止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下一个代码:

Executor exe = Executors.newFixedThreadPool(20);
while (true) {
   try {
       exe.execute(new DispatcherThread(serverSocket.accept()));
       continue;
   } catch (SocketException sExcp) {
       System.exit(-1);
   } catch (Exception excp) {
       System.exit(-1);
   }
}

对于每个 DispatcherThread 我创建了到数据库的连接(这意味着我有20个连接),我需要知道的是当线程停止或线程停止或完成其流处理时,如何关闭与数据库的连接。 / p>

For each DispatcherThread I create a connection to the database (it means I have 20 connections), what I need to know is how I can close the connection to the database when the thread is stopped or it stops or finishes its flow.

推荐答案

您无法直接知道线程何时停止,最接近的线程是 Thread#isAlive 方法,但是当线程中的 run 方法完成但该线程完成时,它可能返回 false 可能无法停止,因为JVM无法保证它。但是,如果您的 DispatcherThread 类实现了 Runnable 接口,那么您可以在<$ c $的底部编写清理代码c>运行方法。

You cannot directly know when the thread is stopped, the closest thing you have is Thread#isAlive method but it may return false when the run method in the thread has finished but the thread may not be stopped since the JVM cannot guarantee it. But if your DispatcherThread class implements Runnable interface then you can write the clean up at the bottom of the run method.

骨架代码:

class DispatcherThread implements Runnable {
    @Override
    public void run() {
        try {
            //open database connection an such...
            //...
            //handle the work here...
        } catch (...) {
            //ALWAYS handle the exceptions
        } finally {
            //cleanup tasks like close database connection
        }
    }
}

顺便说一句, Thread 后缀对于从技术上来说不是线程的类不是一个好名字(因为它不是从 Thread )。取而代之的是,根据操作名称来命名。

By the way, Thread suffix is not a good name for a class that technically is not a thread (because it doesn't extend from Thread). Instead, give a proper name according to what should do.

这篇关于如何知道线程何时停止或停止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆