在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,程序变成死循环。能帮我解析下其中的原因吗?谢谢了!
解决方案 »
- 用swing实现的一个计算器支持lg,sinx,1/x,sqrt哦
- 用java写10个线程从1累加到100
- 从哪里看java封装类里的实现的方法的内容,就是它的函数体在哪里?
- 有关于全屏显示的问题。。。。。。。。。。。。。。。。。。
- 菜鸟问:如何指定JTree的一些节点可编辑(editable)而一些不好编辑
- 在一个大型的软件中,我只负责一小部分,也就几个类。那么我怎么进行单元测试(junit)
- 真是他妈的欺负人!!!
- 高分悬赏----java swing问题。
- applet中,可以有多个CLASS吗?其中一个是继承于APPLET,其他的被他所使用.在HTML中应该怎么写?是不是所有的CLASS都要写上去?
- 在linux中为什么无论使用那种浏览器都无法显示applet中的汉字???
- 类与类关系是继承、依赖、关联、关联?
- 关于线程的问题
改为
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