在我们写程序时,经常会用到单件模式,单件模式是一个类只拥有一个实例对象(或者拥有多个固定数量的实例对象)。下面我给出一个使用多线程的单件模式demo。
package com; public class Single { <span style="white-space:pre"> </span> <span style="white-space:pre"> </span>private static Single _instance = null; <span style="white-space:pre"> </span> <span style="white-space:pre"> </span>private static Object lock = new Object(); <span style="white-space:pre"> </span> <span style="white-space:pre"> </span>//设置为私有构造函数,封死外部调用构造函数新建实例 <span style="white-space:pre"> </span>private Single() <span style="white-space:pre"> </span>{ <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span> <span style="white-space:pre"> </span>public static Single get() <span style="white-space:pre"> </span>{ <span style="white-space:pre"> </span>if ( _instance == null ) <span style="white-space:pre"> </span>{ <span style="white-space:pre"> </span>//设置同步锁,以免多线程并发时,创建多个实例 <span style="white-space:pre"> </span>synchronized (lock) { <span style="white-space:pre"> </span>if ( _instance == null ) <span style="white-space:pre"> </span>{ <span style="white-space:pre"> </span>return _instance = new Single(); <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>return _instance; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span> }
原文地址:http://blog.csdn.net/chenwen_201116040110/article/details/42169267