黑马程序员技术交流社区

标题: 为什么线程中成员变量的值发生改变 [打印本页]

作者: ruanjianxzh    时间: 2011-10-17 11:36
标题: 为什么线程中成员变量的值发生改变
public class test{
  public static void main(String args[])throws Exception{
    thre th2=new thre();
    thre th3=new thre();
    th2.start();
    th3.start();
    th2.join();
    th3.join();
    thre th=new thre();
    System.out.println(th.n);
  }
}
class thre extends Thread{
  public static int n=0;
  public void run(){
    for(int i=0;i<=100;i++){
      n++;
    }
  }
}
重新创建一个线程,为什么他的成员变量的值发生改变,一开始初始化的的值为0!
作者: 宁超    时间: 2011-10-17 15:22
因为你的n被static修饰了,静态变量修饰的变量值被所有该类的对象所共享。所以你的n在2个线程执行完,再被没调用线程的对象输出新的值是th2.start(), th3.start()执行次数n的和了。
如果你把static取了,再输出的话就是0了。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2