How can I use a thread's method from the other thread?
After looking through tutorial on http://oreilly.com/catalog/expjava/excerpt/index.html below is what I have written. I wanted thread_B
to be able to call one of the methods declared in thread_A
thread_A = new Thread(new Worker());
thread_A.start();
thread_B = new Thread(new Communicator(thread_A));
thread_B.start();
Initializing the thread and assigning it to the class variable seems to work fine. However, it does not seem to allow me to use the thread_A's method.
//in thread_B,
Thread worker;
public Communicator(Thread worker){
this.worker = worker;
}
//if I want to call thead_A's method size()
public void run(){
this.worker.queue.size(); /开发者_Go百科/DOES NOT WORK
}
I just want thread_B to know about thread_A's queue information. What is a good approach to solve this problem?
Do it like this:
Worker w = new Worker();
thread_A = new Thread(w);
thread_B = new Thread(new Communicator(w));
and change Communicator
's constructor to take a Worker
rather than a Thread
.
The attribute queue is not part of the Thread class. Is it part of the Worker class?
If so then the code needs to be written something like
worker = new Worker();
thread_A = new Thread(worker);
thread_A.start();
thread_B = new Thread(new Communicator(worker));
thread_B.start();
//in thread_B,
Worker worker;
public Communicator(Worker worker){
this.worker = worker;
}
//if I want to call thead_A's method size()
public void run(){
this.worker.queue.size(); //print out queue size in thread_A
}
Threads don't have methods. Classes have methods. Just retain a reference to whichever object reference you need to call the method on, and call it.
精彩评论