6

I am new to Java Threads. What I am trying to do is from ThreadB object gain access to the instance of a current running thread, ThreadA, and call its method called setSomething. 1) I think I am making harder than it really is 2) I have a null pointer exception so I must be doing something wrong when accessing that method

Here is what I have so far and I have done my due diligence and looked here on StackOverflow for a similar question.

I have a current Thread running in the background:

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

}

}

Thank you in advance

Allen

4

2 回答 2

5

Wow why do you make things to much complex?! this is not as hard as you think (killing a dragon in a dark castle!)

okay all you need to do is passing the threadA references to threadB! just this. and let me say that when you call a method from thread b, so it runs by thread b, not the class has been hosted.

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 setSomething() with this thread! (not thread a)
    }
}

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

        ThreadB b = new ThreadB(a);
        new Thread(b).start();
    }
}

and here a simple threadtutorial

于 2013-10-21T17:14:15.817 回答
1

When or after you instantiate your ThreadB object, give it a reference to your ThreadA object instance. Something like:

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

Then, within the ThreadB code, you can just invoke ThreadA's method by using the reference you have no doubt stored in an instance variable in ThreadB.

于 2013-10-21T17:07:32.257 回答