Java: allow child thread to kill itself on InterruptedException?

I am using ThreadPool through ExecutorService. By calling shutDownNow (), it interrupts all running threads in the pool. When this happens, I want these threads to give up their resources (socket connections and db) and just die, but no longer continue to work more logic, for example: inserting something into the database. What is the easiest way to achieve this? The following is sample code:

edit: forgot to mention that all my connections are released through finally. I just need to make sure that this achievement does not lead to the reliable use of various DB attachments.

public void threadTest() {
    Thread t = new Thread(new Runnable() {

            public void run() {
                try {
                    Thread.sleep(999999);
                } catch (InterruptedException e) {
                    //invoke thread suicide logic here
                }
            }
        });
    t.start();

    t.interrupt();
    try {
        Thread.sleep(4000);
    } catch (InterruptedException e) {
    }
}
+3
source share
3 answers

, , InterruptedException .

finally, , , . , , InterruptedException (.. throws ) voila!

. - , throw InterruptedException, , . , , (.. / , ).

, , " ", . , ​​ , , , . - ; , stop, .

, , , , . finally, , , , - .

+2

, t.interrupt() InterruptedException (, , -).

java.util.concurrent.locks.Lock( ) java.nio java.io

+1

When the thread completes its start method, it will automatically die. So, actually do nothing:

public void threadTest() {
    Thread t = new Thread(new Runnable() {

            public void run() {
                try {
                    Thread.sleep(999999);
                } catch (InterruptedException e) {
                    //invoke thread suicide logic here
                    // Do nothing so the thread will die
                }
            }
        });
    t.start();

    t.interrupt();
    try {
        Thread.sleep(4000);
    } catch (InterruptedException e) {
    }
}

The thread will be freed when threadTest () is completed because the thread variable will no longer be referenced.

0
source

Source: https://habr.com/ru/post/1741274/


All Articles