Stopping looping thread in Java

Posted by halfwarp on Stack Overflow See other posts from Stack Overflow or by halfwarp
Published on 2010-04-27T11:25:26Z Indexed on 2010/04/27 12:33 UTC
Read the original article Hit count: 233

Filed under:
|
|
|

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

Something like:

public void run() {
    Object obj;
    while(true) {
        synchronized(objectsQueue) {
            if(objectesQueue.isEmpty()) {
                try {
                    objectesQueue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                obj = objectesQueue.poll();
            }
        }

        // Do something with the Object obj
    }
}

What is the best way to stop this thread?

I see two options:

1 - Since Thread.stop() is deprecated, I can implement a stopThisThread() method that uses a n atomic check-condition variable.

2 - Send a Death Event object or something like that to the queue. When the thread fetches a death event it exists.

I prefer the 1st way, however, I don't know when to call the stopThisThread() method, as something might be on it's way to the queue and the stop signal can arrive first (not desirable).

Any suggestions?

© Stack Overflow or respective owner

Related posts about java

Related posts about threads