体会:
public class Easy {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
t1.start();
t2.start();
t3.start();
}
}
class MyThread extends Thread{
public void run(){
Object object1 =Tools.getObject();
System.out.println(object1.hashCode());
}
}
class Tools{
static Object object = new Object();//类加载时只创建一次
public static Object getObject(){
return object;
}
public static Object getObject2(){
return new Object(); //每次加载该方法时都会创建新对象
}
}
输出:
531628783
531628783
531628783
每次获得的对象相同
将run()方法中
Tools.getObject()该为Tools.getObject2();再次运行,输出如下:
531628783
37621924
213959490
每次创建的对象的都不同