【发布时间】:2016-01-25 09:49:30
【问题描述】:
在下面的代码中,为什么使用新实例调用shutDown() 方法不会停止while 循环,但是当我使用Processor 类的现有实例调用shutDown() 方法时,循环会终止?
我的理解(来自此链接difference between processes and threads)线程是进程的子集,进程中的所有线程共享相同的堆、内存等。现在,如果所有线程之间共享“私有布尔运行”变量(既然它是一个类变量)那么为什么不新的处理器实例new Processor().shutDown(),将所述变量更改为false?
import java.util.Scanner;
class Processor extends Thread {
private boolean running = true;
public void run() {
while(running) {
System.out.println(" hello ppl");
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void shutDown() {
running = false;
}
}
public class App1 {
public static void main(String[] args) {
Processor p1 = new Processor();
p1.start();
System.out.println("press enter to stop");
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
p1.shutDown(); // THIS WORKS
//new Processor().shutDown(); // THIS DOESNT!!
}
}
【问题讨论】:
-
您的错误在于
private boolean running变量——它是一个类实例字段(Processor的每个实例都有自己的)而不是一个类字段(所有实例共享同一个)。要按照您的意图使用类字段,您必须声明它static。但是,您必须同步对共享空间的访问。
标签: java multithreading