- <p>package cn.itcast;
- public class Demo {
- public static void main(String[] args) {
- Methods m=new Methods();
- Thread t1=new Thread(m);
- Thread t2=new Thread(m);
- Thread t3=new Thread(m);
- Thread t4=new Thread(m);
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
- class Single
- {
- private Single(){}
- private static Single s=null;
- public static Single getInstance(){
- if(s==null)
- synchronized(Single.class){
- if(s==null)//如果不加这个if会怎么样呢?
- s= new Single();
- }
-
- return s;
- }
- }
- class Methods implements Runnable
- {
- public void run(){
- for(int i=0;i<50;i++){
- Single s=Single.getInstance();
- System.out.println(s);
- }
-
- }
- }</p><p>
- </p><p>//为了高效率,加了两个if语句判断,但是如果不加这个if会怎么样呢?
- </p>
复制代码 |
|