常见的创建线程安全单例模式的方法

1,同步代码块结合双检查锁机制实现单例
package com.thread;public class Singleton {private static Singleton instance = null;/*** 同步代码块结合双检查锁机制实现单例* * @return*/public static Singleton getInstance() {try {if (instance == null) {synchronized (Singleton.class) {if (instance == null) {// 创建实例之前可能会有一些准备性的耗时工作Thread.sleep(300);instance = new Singleton();}}}} catch (InterruptedException e) {e.printStackTrace();}return instance;}
}

package com.thread;
public class Singleton {private static Singleton instance = null;/*** 同步代码块结合双检查锁机制实现单例* * @return*/public static Singleton getInstance() {try {if (instance == null) {synchronized (Singleton.class) {if (instance == null) {// 创建实例之前可能会有一些准备性的耗时工作Thread.sleep(300);instance = new Singleton();}}}} catch (InterruptedException e) {e.printStackTrace();}return instance;}
}

package com.thread;public class Test_1 implements Runnable {@Overridepublic void run() {System.out.println(Singleton.getInstance().hashCode());}public static void main(String[] args) {for(int i=0;i<10;i++) {Thread t = new Thread(new Test_1());t.start();}}} 

测试结果,说明是同一个对象


2,同步方法实现单例

package com.thread;
public class Singleton_2 {private static Singleton_2 instance = null;/*** 同步方法实现线程安全的单例* * @return*/public static synchronized Singleton_2 getInstance() {try {if (instance == null) {Thread.sleep(300);instance = new Singleton_2();}} catch (InterruptedException e) {e.printStackTrace();}return instance;}
}

package com.thread;public class Test_1 implements Runnable {@Overridepublic void run() {System.out.println(Singleton_2.getInstance().hashCode());}public static void main(String[] args) {for(int i=0;i<10;i++) {Thread t = new Thread(new Test_1());t.start();}}}

测试结果,线程安全


3,静态代码块

package com.thread;public class Singleton_3 {private static Singleton_3 instance = null;static {instance = new Singleton_3();}public static Singleton_3 getInstance() {return instance;}
}
package com.thread;public class Test_1 implements Runnable {@Overridepublic void run() {System.out.println(Singleton_3.getInstance().hashCode());}public static void main(String[] args) {for(int i=0;i<10;i++) {Thread t = new Thread(new Test_1());t.start();}}}

4,静态内部类

package com.thread;public class Singleton_4 {private static class SingletonHandle{private static Singleton_4 instance = new Singleton_4();}public static Singleton_4 getInstance() {return SingletonHandle.instance;}
}
package com.thread;public class Test_1 implements Runnable {@Overridepublic void run() {System.out.println(Singleton_4.getInstance().hashCode());}public static void main(String[] args) {for(int i=0;i<10;i++) {Thread t = new Thread(new Test_1());t.start();}}}

测试结果



本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部