How to properly stop the Thread in Java?

后端 未结 9 1045
执念已碎
执念已碎 2020-11-21 16:19

I need a solution to properly stop the thread in Java.

I have IndexProcessorclass which implements the Runnable interface:

public class          


        
相关标签:
9条回答
  • 2020-11-21 16:21

    Sometime I will try 1000 times in my onDestroy()/contextDestroyed()

          @Override
        protected void onDestroy() {
            boolean retry = true;
            int counter = 0;
            while(retry && counter<1000)
            {
                counter++;
                try{thread.setRunnung(false);
                    thread.join();
                    retry = false;
                    thread = null; //garbage can coll
                }catch(InterruptedException e){e.printStackTrace();}
            }
    
        }
    
    0 讨论(0)
  • 2020-11-21 16:22

    I didn't get the interrupt to work in Android, so I used this method, works perfectly:

    boolean shouldCheckUpdates = true;
    
    private void startupCheckForUpdatesEveryFewSeconds() {
        threadCheckChat = new Thread(new CheckUpdates());
        threadCheckChat.start();
    }
    
    private class CheckUpdates implements Runnable{
        public void run() {
            while (shouldCheckUpdates){
                System.out.println("Do your thing here");
            }
        }
    }
    
     public void stop(){
            shouldCheckUpdates = false;
     }
    
    0 讨论(0)
  • 2020-11-21 16:27

    In the IndexProcessor class you need a way of setting a flag which informs the thread that it will need to terminate, similar to the variable run that you have used just in the class scope.

    When you wish to stop the thread, you set this flag and call join() on the thread and wait for it to finish.

    Make sure that the flag is thread safe by using a volatile variable or by using getter and setter methods which are synchronised with the variable being used as the flag.

    public class IndexProcessor implements Runnable {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
        private volatile boolean running = true;
    
        public void terminate() {
            running = false;
        }
    
        @Override
        public void run() {
            while (running) {
                try {
                    LOGGER.debug("Sleeping...");
                    Thread.sleep((long) 15000);
    
                    LOGGER.debug("Processing");
                } catch (InterruptedException e) {
                    LOGGER.error("Exception", e);
                    running = false;
                }
            }
    
        }
    }
    

    Then in SearchEngineContextListener:

    public class SearchEngineContextListener implements ServletContextListener {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(SearchEngineContextListener.class);
    
        private Thread thread = null;
        private IndexProcessor runnable = null;
    
        @Override
        public void contextInitialized(ServletContextEvent event) {
            runnable = new IndexProcessor();
            thread = new Thread(runnable);
            LOGGER.debug("Starting thread: " + thread);
            thread.start();
            LOGGER.debug("Background process successfully started.");
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent event) {
            LOGGER.debug("Stopping thread: " + thread);
            if (thread != null) {
                runnable.terminate();
                thread.join();
                LOGGER.debug("Thread successfully stopped.");
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-21 16:28

    Simple answer: You can stop a thread INTERNALLY in one of two common ways:

    • The run method hits a return subroutine.
    • Run method finishes, and returns implicitly.

    You can also stop threads EXTERNALLY:

    • Call system.exit (this kills your entire process)
    • Call the thread object's interrupt() method *
    • See if the thread has an implemented method that sounds like it would work (like kill() or stop())

    *: The expectation is that this is supposed to stop a thread. However, what the thread actually does when this happens is entirely up to what the developer wrote when they created the thread implementation.

    A common pattern you see with run method implementations is a while(boolean){}, where the boolean is typically something named isRunning, it's a member variable of its thread class, it's volatile, and typically accessible by other threads by a setter method of sorts, e.g. kill() { isRunnable=false; }. These subroutines are nice because they allow the thread to release any resources it holds before terminating.

    0 讨论(0)
  • 2020-11-21 16:35

    Using Thread.interrupt() is a perfectly acceptable way of doing this. In fact, it's probably preferrable to a flag as suggested above. The reason being that if you're in an interruptable blocking call (like Thread.sleep or using java.nio Channel operations), you'll actually be able to break out of those right away.

    If you use a flag, you have to wait for the blocking operation to finish and then you can check your flag. In some cases you have to do this anyway, such as using standard InputStream/OutputStream which are not interruptable.

    In that case, when a thread is interrupted, it will not interrupt the IO, however, you can easily do this routinely in your code (and you should do this at strategic points where you can safely stop and cleanup)

    if (Thread.currentThread().isInterrupted()) {
      // cleanup and stop execution
      // for example a break in a loop
    }
    

    Like I said, the main advantage to Thread.interrupt() is that you can immediately break out of interruptable calls, which you can't do with the flag approach.

    0 讨论(0)
  • 2020-11-21 16:41

    You should always end threads by checking a flag in the run() loop (if any).

    Your thread should look like this:

    public class IndexProcessor implements Runnable {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
        private volatile boolean execute;
    
        @Override
        public void run() {
            this.execute = true;
            while (this.execute) {
                try {
                    LOGGER.debug("Sleeping...");
                    Thread.sleep((long) 15000);
    
                    LOGGER.debug("Processing");
                } catch (InterruptedException e) {
                    LOGGER.error("Exception", e);
                    this.execute = false;
                }
            }
        }
    
        public void stopExecuting() {
            this.execute = false;
        }
    }
    

    Then you can end the thread by calling thread.stopExecuting(). That way the thread is ended clean, but this takes up to 15 seconds (due to your sleep). You can still call thread.interrupt() if it's really urgent - but the prefered way should always be checking the flag.

    To avoid waiting for 15 seconds, you can split up the sleep like this:

            ...
            try {
                LOGGER.debug("Sleeping...");
                for (int i = 0; (i < 150) && this.execute; i++) {
                    Thread.sleep((long) 100);
                }
    
                LOGGER.debug("Processing");
            } catch (InterruptedException e) {
            ...
    
    0 讨论(0)
提交回复
热议问题