zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Java多线程之单例模式(线程安全)

2023-09-11 14:19:57 时间
 1 package org.study2.javabase.ThreadsDemo.sync;
 2 
 3 /**
 4  * @Auther:GongXingRui
 5  * @Date:2018/9/20
 6  * @Description: 单例模式 - 二次确认,提高效率
 7  **/
 8 public class DanDemo {
 9     public static void main(String args[]) {
10         Dan dan1 = new Dan();
11         Dan dan2 = new Dan();
12         dan1.start();
13         dan2.start();
14     }
15 }
16 
17 class Dan extends Thread {
18     @Override
19     public void run() {
20         System.out.println(JVM.getInstance());
21     }
22 
23 }
24 
25 /**
26  * 单例模式 - 懒汉式
27  */
28 class JVM {
29     private static JVM instance = null;
30 
31     private JVM() {
32 
33     }
34 
35     // 二次确认提高效率
36     public static JVM getInstance() {
37         if (null == instance) { // 提高效率
38             synchronized (JVM.class) {
39                 if (null == instance) { // 安全
40                     instance = new JVM();
41                 }
42             }
43         }
44         return instance;
45     }
46 
47     public static JVM getInstance2() {
48         synchronized (JVM.class) {
49             if (null == instance) {
50                 instance = new JVM();
51             }
52         }
53         return instance;
54     }
55 
56     public static synchronized JVM getInstance1() {
57         if (null == instance) {
58             instance = new JVM();
59         }
60         return instance;
61     }
62 }
63 
64 /**
65  * 单例模式 - 饿汉式
66  * 线程安全
67  */
68 class JVM2 {
69     private static JVM2 instance = new JVM2();
70 
71     private JVM2() {
72 
73     }
74 
75     public static JVM2 getInstance() {
76         return instance;
77     }
78 }