单例和多线程

来源:互联网 发布:106短信平台软件 编辑:程序博客网 时间:2024/05/16 14:04

单例模式,最常见的就是饥模式和懒汉模式,一个是直接实例化对象,一个是在调用方法时进行实例化对象。在多线程模式中,考虑到性能和安全问题,我们一般选择下面两种比较经典的单例模式

1.静态内部类

package com.aruisi.innofarm;/** * 静态内部类 * @author zmk */public class InnerSingleton {private static class Singleton {private static Singleton single = new Singleton();}public static Singleton getInstance(){return Singleton.single;}public static void main(String[] args) {new Thread(new Runnable(){@Overridepublic void run() {System.out.println("t1线程的哈希值="+InnerSingleton.getInstance().hashCode());}}).start();new Thread(new Runnable(){@Overridepublic void run() {System.out.println("t2线程的哈希值="+InnerSingleton.getInstance().hashCode());}}).start();new Thread(new Runnable(){@Overridepublic void run() {System.out.println("t3线程的哈希值="+InnerSingleton.getInstance().hashCode());}}).start();}}

2.双重check

package com.aruisi.innofarm;/** * 双重check * @author zmk */public class DubbleSingleton {private static DubbleSingleton ds;public static DubbleSingleton getDs(){if(ds == null){try {//模拟初始化对象的需要的时间...Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}synchronized (DubbleSingleton.class) {if(ds == null){ds = new DubbleSingleton();}}}return ds;}public static void main(String[] args) {Thread t1 = new Thread(new Runnable() {@Overridepublic void run() {System.out.println("t1线程的哈希值="+DubbleSingleton.getDs().hashCode());}});Thread t2 = new Thread(new Runnable() {@Overridepublic void run() {System.out.println("t2线程的哈希值="+DubbleSingleton.getDs().hashCode());}});Thread t3 = new Thread(new Runnable() {@Overridepublic void run() {System.out.println("t3线程的哈希值="+DubbleSingleton.getDs().hashCode());}});t1.start();t2.start();t3.start();}}


原创粉丝点击