标签:
我们都知道单例模式,有很多种实现方法。今天我们实现一个单线程实例模式,也就是说只能实例化该类的一个线程来运行,不允许有该类的多个线程实例存在。直接上代码:
public class SingletonThread implementsRunnable
{/**获取access_token 和 expire_in 的url*/
private static final String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+ ParameterConfig.WX_APPID + "&secret=" +ParameterConfig.WX_APPSECRET;/**这里使用public volatile发布一个共享对象*/
public static volatile AccessToken accessToken; //因为是一个线程写多个线程读,而引用的又是“不可变对象”,所以使用volatile保证“可见性”//保证无法实例化 SingletonThread
privateSingletonThread(){}//静态类保证thread的初始化是线程安全的,内部类实现了延迟加载的效果
private static classSingletonThreadHolder
{public static SingletonThread thread = newSingletonThread();
}public staticSingletonThread getInstance()
{returnSingletonThreadHol