如何从java中另一个正在运行的线程访问一个方法

时间:2013-10-21 17:01:37

标签: java multithreading

我是Java Threads的新手。我想要做的是从ThreadB对象获得对当前运行的线程(ThreadA)的实例的访问,并调用其名为setSomething的方法。 1)我认为我比实际做得更努力 2)我有一个空指针异常,因此访问该方法时我必须做错事

到目前为止,我已经完成了尽职调查,并在StackOverflow上查看了类似的问题。

我有一个当前的Thread在后台运行:

// 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**

}

}

提前谢谢

阿伦

2 个答案:

答案 0 :(得分:4)

哇,为什么你要把事情弄得太复杂?!这并不像你想象的那么难(在黑暗的城堡中杀死一条龙!)

好的,你需要做的就是将threadA引用传递给threadB!只是这个。让我说当你从线程b调用一个方法时,所以它由线程b运行,而不是该类已被托管。

class ThreadA implements Runnable{
public void run(){
//do something
}
public void setSomething(){}
}

class ThreadB implements Runnable{
private ThreadA aref;
public ThreadB(ThreadA ref){aref=ref;}
public void run(){
    aref.setSomething();//calling the setSomething() with this thread!! no thread a
}
}

class Foo{
public static void main(String...arg){
  ThreadA a=new ThreadA();
  new Thread(a).start();
  ThreadB b=new ThreadB(b);
  new Thread(b).start();
}
}

here一个简单的线程教程

答案 1 :(得分:1)

在实例化ThreadB对象时或之后,为其提供对ThreadA对象实例的引用。类似的东西:

ThreadA a = new ThreadA();
ThreadB b = new ThreadB(a);

然后,在ThreadB代码中,您可以通过使用毫无疑问存储在ThreadB中的实例变量中的引用来调用ThreadA的方法。