我想在另一个 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?
}
}
请帮忙。谢谢。