Stopping looping thread in Java

后端 未结 6 1650
我寻月下人不归
我寻月下人不归 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:18

    I usually put a flag in the class that has the Thread in it and in my Thread code I would do. (NOTE: Instead of while(true) I do while(flag))

    Then create a method in the class to set the flag to false;

    private volatile bool flag = true;
    
    public void stopThread()
    {
       flag = false;
    }
    
        public void run() {
            Object obj;
            while(flag) {
                synchronized(objectsQueue) {
                    if(objectesQueue.isEmpty()) {
                        try {
                            objectesQueue.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
    
                        obj = objectesQueue.poll();
                    }
                }
    
                // Do something with the Object obj
            }
        }
    

提交回复
热议问题