繁体   English   中英

Java:我可以使用在另一个类的一个类的实例上创建的线程吗?

[英]Java : Can I use the thread created on an instance of one class in another class?

我想在另一个类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?

  }
 }

请帮忙。 谢谢。

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?

  }
 }

您也可以使用Singleton

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM