您的位置:首页 > 编程语言

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

2018-03-23 16:55 232 查看
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 {

@Override
public 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 {

@Override
public 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 {

@Override
public 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 {

@Override
public 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();
}
}

}

测试结果

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