0
点赞
收藏
分享

微信扫一扫

Java 实现单例模式

1. public class Singleton {  
2. private static Singleton intance;
3. private Singleton() {}
4.
5. public static Singleton getInstance() {
6. /*
7. * 一开始多线程进来,遇到锁,一个线程进去,是为空,new对象;后续线程进入,不为空,不操作;最后直接返回
8. * 对象不为空,再有多个线程进入该函数,不为空,不执行加锁操作,直接返回
9. */
10. if (intance == null) {
11. synchronized (Singleton.class) {
12. if (intance == null) {
13. new Singleton();
14. }
15. }
16. }
17. return intance;
18. }
19. }
20.
21. class Singleton1 {// 懒汉式
22. private static Singleton1 intance = new Singleton1();//懒的,程序运行的时候就加载出来了
23. private Singleton1() {}
24.
25. public static Singleton1 getInstance() {
26. return intance;
27. }
28. }
29.
30. class Singleton2 {// 饿汉式
31. private static Singleton2 intance;
32. private Singleton2() {}
33.
34. public static Singleton2 getInstance() {//用到的时候 才加载
35. if (intance == null) {
36. new Singleton2();
37. }
38. return intance;
39. }
40. }
41.
42. class Singleton3 {// 饿汉式 线程安全
43. private static Singleton3 intance;
44. private Singleton3() {}
45.
46. //用到的时候才加载,加锁多线程调用,都有一个加锁的动作
47. public synchronized static Singleton3 getInstance() {
48. if (intance == null) {
49. new Singleton3();
50. }
51. return intance;
52. }
53. }
54.
55. class Singleton4 {// 饿汉式 线程安全
56. private static Singleton4 intance;
57. private Singleton4() {}
58.
59. public static Singleton4 getInstance() {//用到的时候 才加载
60. synchronized (Singleton4.class) {// 加锁 效率跟3差不多
61. if (intance == null) {
62. new Singleton4();
63. }
64. }
65. return intance;
66. }
67. }

举报

相关推荐

0 条评论