Threads Java Inturrupts

爷,独闯天下 提交于 2020-01-01 19:18:13

问题


This is the second post I have on trying to end/quit threads using interrupts and dealing with Ctrl-c ends. I'm not sure I understand it but here is my best attempt. I need more clarity on the concepts, and please give code examples where you can.

There are two classes, the main class Quitit and another class thething. The main class.

When loading the program via the terminal (the case on Linux):

Java -jar Quitit.jar

When you Ctrl-c to close it am i correct in saying that you need to:

Runtime.getRuntime().addShutdownHook()

Your threads so that they are killed on shut down.

  1. Is this to correct way to deal with that ?
  2. Why does it not allow you to call a method so that it may close down gracefully?

When not shutting down via Ctrl-C and you wish to do so via Thread.Interrupt() then does the program below use it correctly ?

  • Am I correct in saying that Thread.Join() halts the calling thread until the targeted thread is dead before continuing?
  • How would you implement/call the same Runtime.getRuntime().addShutdownHook() on implements Runnable threads, instead of extends Thread ?

Quitit class:

public class Quitit extends Thread {

    public Quitit(String name) {
        try {
            connect("sdfsd");
        } catch (Exception ex) {

        }
    }

    void connect(String portName) throws Exception {
        Thread thh = new thething("blaghname");
        Runtime.getRuntime().addShutdownHook(thh);
        thh.start();
        System.out.println("Thread Thh (thething) Started()");

        while (true) {
            try {
                Thread.sleep(2000);

                if (thh.isAlive()) {
                    System.out.println("Thread Thh (thething) isAlive");
                    if (thh.isInterrupted()) {

                        System.out.println("Thread Thh (thething) is Inturrupted Should be Shutting Down");

                    } else {
                        System.out.println("Thread Thh (thething) is Not Inturrupted");
                        thh.interrupt();
                        System.out.println("Thread Thh (thething) Inturrput Sent");
                        System.out.println("Thread Thh (thething) Joined()");
                        thh.join();

                    }

                } else {
                    System.out.println("Thread Thh (thething) isDead");
                    System.out.println("Main Thread:: can now end After Sleep off 2 seconds");
                    Thread.sleep(2000);
                    System.out.println("MMain Thread:: Sleep Ended Calling Break");
                    break;
                }

            } catch (InterruptedException xa) {
                System.out.println("Main Thread:: ending due to InterruptException second Break called");
                break;
            }
        }

        System.out.println("Main Thread:: Outside While(true) via Break call");
    }

    public static void main(String[] args) {
        try {

            Thread oop = new Quitit("");
            Runtime.getRuntime().addShutdownHook(oop);
            oop.start();

        } catch (Exception ezx) {
            System.out.println("Main Thread:: Not Expected Exception");
        }
    }
}

TheThing class:

public class thething extends Thread {

    thething(String name) {
        super(name);
    }

    @Override
    public void run() {

        while (true) {
            try {
                System.out.println("thething class:: Inside while(true) Loop, now sleeping for 2 seconds");
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                try {

                    System.out.println("thething class:: has been Inturrupted now sleeping for 2 seconds!!");
                    Thread.sleep(2000);
                    break; // Will Quit the While(true) Loop
                } catch (InterruptedException ex) {
                    System.out.println("thething class:: Second InterruptedException called !!");
                }
            }
        }

        System.out.println("thething class:: Outside while(true) and now thread is dying");
    }
}

OutPut::

run:
Thread Thh (thething) Started()
thething class:: Inside while(true) Loop, now sleeping for 2 seconds
Thread Thh (thething) isAlive
Thread Thh (thething) is Not Inturrupted
Thread Thh (thething) Inturrput Sent
Thread Thh (thething) Joined()
thething class:: has been Inturrupted now sleeping for 2 seconds!!
thething class:: Outside while(true) and now thread is dying
Thread Thh (thething) isDead
Main Thread:: can now end After Sleep off 2 seconds
MMain Thread:: Sleep Ended Calling Break
Main Thread:: Outside While(true) via Break call
FINISHED - BUILD SUCCESSFUL (total time: 8 seconds)

回答1:


I am surprised to here that control-c is not killing your program. It does on my test programs and should under most Unix variants.

When you Ctrl-c to close it am i correct in saying that you need to (setup a shutdown hook) so the threads are killed on shut down.

No, this is not correct. Shutdown hooks are used when you want to explicitly cleanup up some processing. They have nothing to do with the running threads and how they terminate.

Why does it not allow you to call a method so that it may close down gracefully?

Because that's not it's job.

Is this to correct way to deal with that ?

I'm not sure what the "that" is. As others have mentioned, the JVM finishes when the last non-daemon thread finishes. At that point the JVM kills all daemon threads and exits. If you want a background thread to be killed on shutdown then you'd do something like:

Thething theThing = new TheThing();
// set it to be a daemon thread before it starts
theThing.setDaemon(true);
theThing.start();

If you are asking about the proper way to terminate a thread cleanly then you can either use a volatile boolean or interrupt the thread. Typically this means that the class that starts the thread, keeps a handle around do it. Since QuitIt started TheThing class it would do something like the following if it was using a volatile boolean:

void connect(String portName) throws Exception {
    Thread thh = new TheThing("blaghname");
    thh.start();
    ...
    // we are ready to kill the thread now
    tth.shutdown = true;
}

Then in TheThing, the run() method would do something like the following:

public class TheThing extends Thread {
    volatile boolean shutdown = false;
    public void run() {
       while (!shutdown) {
          ...
          // you can also test for shutdown while processing
          if (shutdown) {
             return;
          }
       }
    }
}

When not shutting down via Ctrl-C and you wish to do so via Thread.interrupt() then does the program below use it correctly ?

Using Thread.interrupt() is another way you can signal your thread that you want it to shutdown. You can also use the thread interrupt flag in a similar manner to the boolean above:

void connect(String portName) throws Exception {
    Thread thh = new TheThing("blaghname");
    thh.start();
    ...
    // we are ready to interrupt the thread now
    tth.interrupt();
}

It is very important to realize that interrupting a thread sets a flag on the Thread. They thread still needs to handle the interrupt appropriately with code. Then in TheThing, the run() method would do something like the following:

public class TheThing extends Thread {
    public void run() {
       while (!Thread.currentThread().interrupted()) {
          ...
       }
    }
}

Interrupting also causes wait(), notify(), and other methods to throw InterruptedException. The proper way to deal with this is:

try {
   Thread.sleep(1000);
} catch (InterruptedException e) {
   // catching the interrupted exception clears the interrupt flag,
   // so we need to re-enable it
   Thread.currentThread().interrupt();
   // probably you want to stop the thread if it is interrupted
   return;
}

Am I correct in saying that Thread.join() halts the calling thread until the targeted thread is dead before continuing?

Yes. Calling join() (with no arguments) will pause the calling thread until the thread it is joining on finishes. So typically you set your shutdown flag or you interrupt the thread and then join with it:

tth.shutdown = true;
// or tth.interrupt()
tth.join();

How would you implement/call the same Runtime.getRuntime().addShutdownHook() on implements Runnable threads, instead of extends Thread ?

This question doesn't make any sense. If you are asking about how to shutdown a thread if you have implemented Runnable, then the same mechanisms that I mention above would work.


Another thing that factors into the discussion of control-c is signal handlers. They allow you to catch control-c (and other signals) so you can do something intelligent with them. They are very OS dependent (of course) and if you catch the interrupt signal (SIGINT is usually sent by control-c) and don't stop the JVM, you are going to have problems.

But in any case, you can do something like the following:

...
MyHandler handler = new MyHandler();
// catch the control-c signal, "TERM" is another common kill signal
Signal.handle(new Signal("INT"), handler);
...

private static class MyHandler implements SignalHandler {
    @Override
    public void handle(Signal arg0) {
        // interrupt your threads
        // clean up stuff
        // set shutdown flags
        // ...
    }
}

Again, I would say that it is a bad practice to catch interrupt signal (control-c) and not take the JVM down.




回答2:


You have many questions in your question. If you want to gracefully shutdown threads when Ctrl-C is hit, then register a shutdown hook, and in the code of this shutdown hook, gracefully shutdown your threads.

A Thread instance can be constructed by extending Thread, or by passing a Runnable to the Thread constructor. So, if you want the code of your shutdown hook to be implemented in a Runnable, just do the following:

Runnable r = new Runnable() {
    @Override
    public void run() {
        try {
            // code of the shutdown hook: ask running threads to exit gracefully
            for (Thread t : threadsToShutDown) {
                t.interrupt();
            }
            for (Thread t : threadsToShutDown) {
                t.join(); 
            }
        }
        catch (InterruptedException e) {
            // too bad
        }
    }
};
Runtime.getRuntime().addShutdownHook(new Thread(r));

Note that the above will prevent the JVM to exit if one of the threads doesn't respond to the interrupt. Introducing a timeout would be a good idea.

Also note that you must NOT start the thread that you register as shutdown hook.




回答3:


When you Ctrl-c to close it am i correct in saying that you need to: Runtime.getRuntime().addShutdownHook() your threads so that they are killed on shut down.

No.

As per the docs, addShutdownHook simply registers a thread that will be run when the VM is shut(-ting) down. In theory this would be used as an application-wide finalizer; something that would run when your process is ending, to "tidy up". However there are some issues with them, similar to the reasons why finalizers are not recommended, in fact. They aren't guaranteed to run if the process is terminated abruptly, so they can't do anything critical. They run at a delicate part in the lifecycle, so they may not be able to access or interact with objects in a way that you'd expect. And they need to run quickly, else risk the process being killed before they finish.

But anyway this is completely different to what you're thinking of. When the VM shuts down, your threads will exit, without you needing to.

And besides, you have to provide an unstarted thread as a shutdown hook, so I'm slightly surprised that you don't get an IllegalThreadState exception thrown on shutdown.

When not shutting down via Ctrl-C and you wish to do so via Thread.Interrupt()

That's not the "usual" way to exit a multithreaded program either.

You have (broadly) two options:

  1. Start your threads as "daemons", then just leave them be. The program exits when no non-daemon threads are running, so when your main thread terminates, your program will exit even though your "worker" threads are still alive. This works best of course when your

  2. Signal to your threads that they should exit, e.g. call a stop() method that sets a boolean flag, and have those threads allow themselves to terminate. A thread stops when its run() method returns. Generally threads only keep running while they're in some sort of loop. Simply letting your thread exit the ongoing loop when its told to exit will shut it down gracefully, as typically it will finish its current "chunk of work" before checking the flag.

Interrupting a thread doesn't do what you might expect. It just sets another boolean flag internally. Many blocking operations (such as filesystem/network/database methods) will periodically check this flag and throw an InterruptedException if it is set. This allows a blocking method to exit early, but is not guaranteed if the method isn't "well-behaved".

So in your example it works because Thread.sleep() does respond to interrupts, and you then consider this a signal to exit. If however you write your own method to calculate the millionth Fibonacci number, for example, interrupting the thread would do nothing unless your implementation explicitly checks Thread.currentThread().interrupted() between each iteration.

Also, interrupts can come from almost anywhere, and it's hard to ascribe a particular "meaning" to them. Are they a signal to kill the thread? A signal to give up on the current method because the client's bored? A signal to start from the top because new data has arrived? In non-trivial programs it's not entirely clear.

A much better approach, given this, is to use boolean flags to communicate the reason, and then interrupt after setting the flag. A thread that gets interrupted should then check its state to see what just happened, and work out what to do. For example, you could code thething.run() as

private boolean keepRunning = true; 

public void run() {
    while(keepRunning) {
        try {             
            System.out.println("thething class:: Inside while(true) Loop, now sleeping for 2 seconds");
            Thread.sleep(2000); 
        } catch (InterruptedException e) {
            try {
                System.out.println("thething class:: has been Inturrupted now sleeping for 2 seconds!!");                        
                Thread.sleep(2000); 
            } catch (InterruptedException ex) 
            { 
                 System.out.println("thething class:: Second InterruptedException called !!");  
            }
        } 
    }
}

And in QuitIt, set thh.keepRunning = false before interrupting it (or even better, define a method such as thh.allWorkDone() which sets the flag, and call that).

Note that there is no way to forcibly stop another thread - with good reason - you need to signal for the thread to stop, and ensure that whatever's running in the thread observes and respects that signal.




回答4:


Best by huge margin - use daemon threads with no explicit termination. Next, redesign app so I can use daemon threads with no explicit termination. Absolute last resort, when no other approach is remotely possible, any kind of explicit shutdown code such has been posted here.



来源:https://stackoverflow.com/questions/11755512/threads-java-inturrupts

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