Java: Is `while (true) { ... }` loop in a thread bad? What's the alternative? Java: Is `while (true) { ... }` loop in a thread bad? What's the alternative? multithreading multithreading

Java: Is `while (true) { ... }` loop in a thread bad? What's the alternative?


Instead of looping forever and breaking or returning, you might choose to check the interrupted status.

while (!Thread.currentThread().isInterrupted()) {    try {        doWork();        wait(1000);    } catch (InterruptedException ex) {        Thread.currentThread().interrupt();    }}

If your threads are tasks managed by an ExecutorService, you can have them all end gracefully simply by calling shutdownNow().


while (!stop_running) { ... }

...perhaps? A some sort of exit flag is often used to control thread running.


Not inherently, no. You can always bail using break or return. Just make sure you actually do (at some point)

The problem is what happens when your thread has nothing to do? If you just loop around and around checking a condition, your thread will eat up the whole CPU doing nothing. So make sure to use wait to cause your thread to block, or sleep if you don't have anything to wait on.