How to know when a thread stops or is stopped?

我是研究僧i 提交于 2019-12-11 12:34:21

问题


I have the next code:

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);
   }
}

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.


回答1:


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.

Skeleton code:

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
        }
    }
}

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.




回答2:


You could close the thread-specific connection at the end of your run() method.

A finally block would ensure that it happened however the run() method exited.

class DispatcherThread extends Runnable {
    public void run() {
       ...
       try {
          ...
       }
       finally {
            // Close the connection
       }
    }


来源:https://stackoverflow.com/questions/24661989/how-to-know-when-a-thread-stops-or-is-stopped

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!