来自两个Main类的Java Access单例类实例

时间:2014-02-22 06:43:02

标签: java singleton

package Test
public class SingleObject {

   //create an object of SingleObject
   private static SingleObject instance = null;
   public String msg = "1";

   //make the constructor private so that this class cannot be
   //instantiated
   private SingleObject(){}

   //Get the only object available
   public static SingleObject getInstance(){
       if(instance!=null){
       }else{
           instance = new SingleObject();
       }     
       return instance;
 }


package Test
public class Main1 {
     public static void main(String[] args) {
         SingleObject object  = null;
         while(true){
             object = SingleObject.getInstance();
             object.msg = "2";
             System.out.println(object.msg); //Here output is 2
         }
     }
 }

 import SingleObject.*;
 public class Main2{
    public static void main(String[] args) {

           //Here new instance being created
           SingleObject object = SingleObject.getInstance();

           //Here output is 1
           System.out.println(object.msg);
     }
 }

编译Main1和Main2后再次

  1. 我运行Main1 - 所以它将继续运行,变量msg将更新为“2”[此处创建SingletonObject类的实例]

  2. 然后我运行Main2。但是这里创建了SingleObject类的新实例。所以我输出为“1”。作为poer singleton desingn模式。当我运行Main2时,我应该在Main1中创建实例,为什么Main2正在创建SingletonObject的新实例?

1 个答案:

答案 0 :(得分:4)

您在两个完全独立的JVM中运行两个完全独立的程序。单例是其JVM中的单例。

JVM没有共享内存。他们彼此独立。