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

单列模式在Thread模式下的变通

2016-05-08 19:18 337 查看
public class SingleTonThread {

public static void main(String[] args) {
RunDemo rundemo=new RunDemo();
Thread t1=new Thread(rundemo);
Thread t2=new Thread(rundemo);
t1.start();
t2.start();
}

}

class RunDemo implements Runnable{
public void run(){
SingleDemo.NewInstance();
}

}

class SingleDemo{
private static SingleDemo ston=null;
private SingleDemo(){
System.out.println("单列模式");
}

public static SingleDemo NewInstance(){
if(ston==null){
synchronized(SingleDemo.class){
if(ston==null){
//如果没有同步这个锁,有可能两个线程都判断ston为null,然后各自new了一个示例。
ston=new SingleDemo();
}
}
}
return ston;
}

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