我是Java线程的新手。我想要做的是从ThreadB对象获取对当前正在运行的线程的实例ThreadA的访问,并调用其名为setSomething的方法。 1)我觉得我在做难度比它确实是 2)我有一个空指针异常,所以我必须在访问该方法如何从java中的另一个正在运行的线程访问方法
这里的时候,做错了什么是我到目前为止,我已经做了我因勤奋,并在这里看到StackOverflow的类似问题。
我有一个当前线程在后台运行:
// assume this thread is called by some other application
public class ThreadA implements Runnable{
private Thread aThread;
public ThreadA(){
aThread = new Thread(this);
aThread.setName("AThread");
aThread.start();
}
@Override
public void run(){
while(true){
// doing something
}
}
public void setSomething(String status){
// process something
}
}
// assume this thread is started by another application
public class ThreadB implements Runnable{
@Override
public void run(){
passAValue("New");
}
public void passAValue(String status){
// What I am trying to do is to get the instance of ThreadA and call
// its method setSomething but I am probably making it harder on myself
// not fully understanding threads
Method[] methods = null;
// get all current running threads and find the thread i want
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for(Thread t : threadSet){
if(t.getName().equals("AThread")){
methods = t.getClass().getMethods();
}
}
//**How do I access ThreadA's method, setSomething**
}
}
预先感谢您
艾伦
难道真的没有办法让你通过'ThreadA'对象_into_'ThreadB'这样你就可以直接访问它。对班级做一些反思是不合适的。 – Gray
当你说“由另一个应用程序启动”时,你不是指在不同的JVM中,对吧?如果它在另一个JVM中,那么您将不得不使用RMI或其他进程间通信。或共享一个文件或其他东西。 – Gray
格雷的第二个评论应该是被接受的答案! – 2013-10-21 17:09:54