请写一个singleton模式的类(多线程访问)?
2 回答
凤凰求蛊
TA贡献1825条经验 获得超4个赞
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | class Singleton { private static Singleton s; public String str = "你好";
public String getStr(String tName) throws Exception { synchronized (Singleton.class) { //获取资源,保证多线程下不会导致线程冲突 System.out.println(tName + "进入"); Thread.sleep(1000); System.out.println(tName + "结束"); } return str; }
private Singleton() { System.out.println("A Singleton Model example"); }
public static Singleton getSigleton() { if (s == null) s = new Singleton(); return s; } } |
- 2 回答
- 0 关注
- 817 浏览
添加回答
举报
0/150
提交
取消