java 写一个类,在任何时候可以向他查询“你已经创建了多少个对象”,要求线程安全
答案:1 悬赏:30
解决时间 2021-03-03 21:00
- 提问者网友:相思故
- 2021-03-02 22:08
java 写一个类,在任何时候可以向他查询“你已经创建了多少个对象”,要求线程安全
最佳答案
- 二级知识专家网友:一起来看看吧
- 2021-03-02 22:18
类里面有一个计数的静态属性,在调用所有该类的构造方法时,使他自增,这是计数。为了保证线程安全把他放入ThreadLocal,需要显示时,再拿出来。下面是个简单的小示例:
public class Test {
private int id;
private String name;
private static long count;
private final static ThreadLocal tl=new ThreadLocal();
public Test() {
super();
count++;
tl.set(count);
}
public long getCount(){
return (Long)tl.get();
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
Test t=new Test();
System.out.println(t.getCount());
}
}
}
public class Test {
private int id;
private String name;
private static long count;
private final static ThreadLocal tl=new ThreadLocal();
public Test() {
super();
count++;
tl.set(count);
}
public long getCount(){
return (Long)tl.get();
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
Test t=new Test();
System.out.println(t.getCount());
}
}
}
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯
• 手机登qq时,显示手机磁盘不足,清理后重新登 |
• 刺客的套装怎么选啊? |