I have been recently trying to learn about threads and have been experimenting with them, and have come across something that confuses me. In the following code, the While loop running in the main thread never ends? However, when I add some body into the loop (eg. System.out.println("anything")), the loop does end and the app terminates.
package entire;
import java.util.ArrayList;
import java.util.List;
public class Worker implements Runnable{
boolean running = false;
Worker() {
(new Thread(this)).start();
}
@Override
public void run() {
running = true;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
running = false;
System.out.println(running);
}
public static void main(String[] args) throws InterruptedException {
List<Worker> workers = new ArrayList<Worker>();
workers.add(new Worker());
workers.add(new Worker());
workers.add(new Worker());
for(Worker worker : workers) {
System.out.println(worker);
while(worker.running) {
}
}
}
}
If my while loop looks like this the app terminates?
for(Worker worker : workers) {
System.out.println(worker);
while(worker.running) {
System.out.println("literally anything");
}
}
Can someone please explain why this is?