user482594
user482594

Reputation: 17486

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(); //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?

Upvotes: 0

Views: 91

Answers (3)

user207421
user207421

Reputation: 311054

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.

Upvotes: 0

Brett Walker
Brett Walker

Reputation: 3586

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
}

Upvotes: 0

Mat
Mat

Reputation: 206909

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.

Upvotes: 2

Related Questions