猿问

请问如下代码是为什么?,非常感谢

//仅用于测试,无任何业务
public class DateFormat2 {
    public static SimpleDateFormat parse(){
        SimpleDateFormat  adf=new SimpleDateFormat ();
      return adf
}
}
//多线程测试上述方法,局部变量应该在线程栈中,每个线程访问该方法后都new一个对象,应该是不同的引用地址,但结果却不是,测试方法如下
public class Test {
  public static class TestSimpleDateFormatThreadSafe extends Thread {
       @Override
       public void run() {
           while(true) {
               try {
                   this.join(2000);
               } catch (InterruptedException e1) {
                   e1.printStackTrace();
               }
                   try {
System.out.println(this.getName()+":"+DateFormat2.parse());
} catch (ParseException e) {
e.printStackTrace();
}
           }
       }   
   }

public static void main(String[] args) throws ParseException {
for (int i = 0; i <3; i++) {
new TestSimpleDateFormatThreadSafe().start();
}
}
}

ibeautiful
浏览 133回答 2
2回答

慕标5832272

这个问题的关键是不是在于,静态方法中定义的内部变量是否属于类或类实例共享级别?&nbsp; 如果是,那么这个是不就相当于public static SimpleDateFormat adf = new SimpleDateFormat();

aluckdog

说明你的例子 是不同的SimpleDateFormat对象但是他们的hashCode()相同&nbsp;
随时随地看视频慕课网APP
我要回答