Stopping looping thread in Java

后端 未结 6 1615
我寻月下人不归
我寻月下人不归 2020-12-29 16:13

I\'m using a thread that is continuously reading from a queue.

Something like:

public void run() {
    Object obj;
    while(true) {
        synchron         


        
6条回答
  •  礼貌的吻别
    2020-12-29 16:14

    In your reader thread have a boolean variable stop. When you wish for this thread to stop set thius to true and interrupt the thread. Within the reader thread when safe (when you don't have an unprocessed object) check the status of the stop variable and return out of the loop if set. as per below.

    public class readerThread extends Thread{
        private volitile boolean stop = false;
        public void stopSoon(){
            stop = true;
            this.interrupt();
        }
        public void run() {
            Object obj;
            while(true) {
                if(stop){
                    return;
                }
                synchronized(objectsQueue) {
                if(objectesQueue.isEmpty()) {
                    try {
                        objectesQueue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if(stop){
                        return;
                    }    
                    obj = objectesQueue.poll();
                    // Do something with the Object obj
                }
            }
        }
    
    
    }
    public class OtherClass{
         ThreadReader reader;
         private void start(){
              reader = ...;
              reader.start();
         }
    
         private void stop(){
              reader.stopSoon();
              reader.join();     // Wait for thread to stop if nessasery.
         }
    }
    

提交回复
热议问题