0

我想在另一个 B 类中使用在(比如说)类 A 的实例 x 上创建的线程。我已经以下面评论的形式更好地说明了我的问题。

我有这样的事情:

Class A implements Runnable{
  public static int num;

  public void setNum(int i) { num = i; }

  public int getNum() { return num; }

  public void run(){
     while(true){} //I want to keep this thread running continuously
  }
}

Class B{
 A a;

 //I will call this method in class C to use the same instance of class A 
 public A getInstanceOfA() { return a; } 

 public static void main(String[] args){
   a = new A();
   Thread t = new Thread(a);
   t.start();

   a.setNum(5);
   System.out.println(a.getNum()); //getting output as 5. Okay as Expected. 
  }
 }

 class C{
  A a;
  public static void main(String[] args){
   a = getInstanceOfA();

   System.out.println(a.getNum()); 
   //Here I'm getting output 0 not 5 why? As Thread created on instance a is 
   //already running, and also I am using the same instance of class A 
   //so I should get the updated value 5, but getting 0. Why it is re-initializing num?

  }
 }

请帮忙。谢谢。

4

1 回答 1

0
I am not giving you the exact code but you should do it something like this.

Class B{
 A a;


public B(){
initialize();

}


 //I will call this method in class C to use the same instance of class A 
 public A getInstanceOfA() { return a; } 

// this method should not be main
 public void initialize{
   a = new A();
   Thread t = new Thread(a);
   t.start();

   a.setNum(5);
   System.out.println(a.getNum()); //getting output as 5. Okay as Expected. 
  }
 }

 class C{
  A a;
  public static void main(String[] args){

   B b = new B();
   a = b.getInstanceOfA();

   System.out.println(a.getNum()); 
   //Here I'm getting output 0 not 5 why? As Thread created on instance a is 
   //already running, and also I am using the same instance of class A 
   //so I should get the updated value 5, but getting 0. Why it is re-initializing num?

  }
 }

你也可以使用单例

http://en.wikipedia.org/wiki/Singleton_pattern

于 2013-10-23T18:23:48.487 回答