问题
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