public class Test extends Thread {
private static int count = 0; private int countNumber = ++count; //*******请注意此处******** public void run() {

System.out.println("Thread" + countNumber + "[" + count + "]");
try{
Thread.sleep(3000);
}catch(Exception e){
e.printStackTrace();
}
} public static void main(String[] args) {
for (int i = 0; i < 4; i++) {
new Test().start();
}
}
}请教一个为何用*****号标记的地方countNumber改为static变量,结果完全不一样,每次创建一个线程他们共享成员变量吗?

解决方案 »

  1.   

    static变量是被该类的所有实例共享的,
    所以这些类共享的是count变量。如果countNumber不是共享的(static),那么在构造实例的时候,调用了++count,改变了count的值,然后赋值给countNumber。由于线程执行先后的不确定性,导致了各个实例的countNumber的不确定性。如果countNumber是static的,那么它也被所有的实例共享。即时线程执行先后不确定性存在,得到的结果也是确定的。个人简单理解:如果countNumber 不是static的,那么内存中有多个countNumber,如果countNumber 是static的,那么内存中只有一个countNumber。大家讨论,呵呵
      

  2.   

    static变量是被该类的所有实例共享的,
      

  3.   

    请教一个为何用*****号标记的地方countNumber改为static变量,结果完全不一样,每次创建一个线程他们共享成员变量吗?
    =====================================================================================
    一个线程也就是你new出来的一个你的线程类实例,和其他类的实例没什么不同,静态的就共享,非静态的就属于不同对象.
    其他的cuilichen(fjfjfjfj)都说完了,赞同.
      

  4.   

    countNumber改为static变量后就变成了类变量,所有实例共享的。
      

  5.   

    同意楼上的,static 变量是被该类的所有实例共享。
      

  6.   

    static 的变量只有在类加载的时候赋值(在代码中没有赋值语句)
     “private static int countNumber = ++count;”时,countNumber 始终为1
    其他同意cuilichen(fjfjfjfj)
      

  7.   

    楼上:
    static 的变量只有在类加载的时候赋值(在代码中没有赋值语句)
     “private static int countNumber = ++count;”时,countNumber 始终为1
    ===================================================================================静态变量植是可以改变的啊,否则成final Static了
    static 的变量只有在类加载的时候分配一次内存并初始化
    private static int countNumber = ++count;”时,countNumber为静态变量,所以他的植会随这个语句的调用而增加且所有线程对象共享.
      

  8.   

    是可以改变,但“private static int countNumber = ++count;”这样定义,++count只会执行一次