Why does this cycle not end?

I recently tried to learn about threads and experiment with them, and came across something that bothers me. In the following code, the While loop that runs in the main thread does not end? However, when I add some kind of body to the loop (for example, System.out.println ("nothing"), the loop ends and the application 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, is the application terminating?

    for(Worker worker : workers) {
        System.out.println(worker);
        while(worker.running) {
            System.out.println("literally anything");
        }
    }   

Can someone explain why this is?

+4
source share

Source: https://habr.com/ru/post/1656724/


All Articles