在Thinking in Java 多线程这章中有个多线程的例子:
public class SimpleThread extends Thread{
private int countDown=5;
private static int threadCount = 0;
private int threadNumber = ++threadCount;
public SimpleThread(){
System.out.println("Making" + threadNumber);
}
public void run(){
while (true){
System.out.println("Thread" +
threadNumber + "(" + countDown + ")");
if (--countDown ==0) return;
}
}
public static void main(String[] args){
for(int i = 0;i < 5;i++)
new SimpleThread().start();
System.out.println("All Thread Started");
}
}现在有个问题是:我在把变量countDown前面也加上static,程序变成死循环。能帮我解析下其中的原因吗?谢谢了!
public class SimpleThread extends Thread{
private int countDown=5;
private static int threadCount = 0;
private int threadNumber = ++threadCount;
public SimpleThread(){
System.out.println("Making" + threadNumber);
}
public void run(){
while (true){
System.out.println("Thread" +
threadNumber + "(" + countDown + ")");
if (--countDown ==0) return;
}
}
public static void main(String[] args){
for(int i = 0;i < 5;i++)
new SimpleThread().start();
System.out.println("All Thread Started");
}
}现在有个问题是:我在把变量countDown前面也加上static,程序变成死循环。能帮我解析下其中的原因吗?谢谢了!
改为
if (--countDown ==0){
System.out.println(countDown);
return;
}这样能更清楚的看到结果。
执行for(int i = 0;i < 5;i++)
new SimpleThread().start(); 时,
当i=0时,执行一次new SimpleThread().start(); 自动调用SimpleThread 的read(),然后直到countDown=0时退出read(),此时,countDown的值为0;
当i=1时,再次执行new SimpleThread().start(); 自动调用SimpleThread 的read(),由于countDown变成是static,所以此时,新的线程读到的countDown值是0,这就是导致死循环的原因。因为在进行if (--countDown ==0)判断时,countDown前自减变成-1,永远不等于0。
解决方法:
修改if (--countDown ==0) return; 为if (countDown-- <=0) return