简体   繁体   中英

How to know when a thread stops or is stopped?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM