为什么这个while循环没有结束?

时间:2016-10-04 18:41:39

标签: java multithreading loops while-loop

我最近一直试图了解线程,并一直在试验它们,并且遇到了令我困惑的事情。在下面的代码中,在主线程中运行的While循环永远不会结束?但是,当我在循环中添加一些主体时(例如,System.out.println("任何")),循环结束并且应用程序终止。

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) {
        }
    }       
  }
}

如果我的while循环看起来像这样应用程序终止?

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

有人可以解释一下这是为什么吗?

0 个答案:

没有答案