您的位置:首页 > 运维架构 > 网站架构

架构师养成记--6.单例和多线程、ThreadLocal

2016-12-08 23:30 330 查看
一、ThreadLocal

使用wait/notify方式实现的线程安全,性能将受到很大影响。解决方案是用空间换时间,不用锁也能实现线程安全。

来看一个小例子,在线程内的set、get就是threadLocal

1 public class DubbleSingleton {
2
3     private static DubbleSingleton ds;
4
5     public  static DubbleSingleton getDs(){
6         if(ds == null){
7             try {
8                 //模拟初始化对象的准备时间...
9                 Thread.sleep(3000);
10             } catch (InterruptedException e) {
11                 e.printStackTrace();
12             }
13             synchronized (DubbleSingleton.class) {
14                 if(ds == null){
15                     ds = new DubbleSingleton();
16                 }
17             }
18         }
19         return ds;
20     }
21
22     public static void main(String[] args) {
23         Thread t1 = new Thread(new Runnable() {
24             @Override
25             public void run() {
26                 System.out.println(DubbleSingleton.getDs().hashCode());
27             }
28         },"t1");
29         Thread t2 = new Thread(new Runnable() {
30             @Override
31             public void run() {
32                 System.out.println(DubbleSingleton.getDs().hashCode());
33             }
34         },"t2");
35         Thread t3 = new Thread(new Runnable() {
36             @Override
37             public void run() {
38                 System.out.println(DubbleSingleton.getDs().hashCode());
39             }
40         },"t3");
41
42         t1.start();
43         t2.start();
44         t3.start();
45     }
46
47 }


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: