Reputation: 97
Let's say I have a method in a thread that I want to call, whenever a certain event occurs in thread running parallel to it. Can I store the objects of the class on which the thread is running (lets say in a hashmap) and then directly refer to the object to invoke the method?
For example:
Class SomeThread implements Runnable{
SomeThread(){
}
void run(){
//do something
}
void someMethod(){
//do something else
}
}
Lets say multiple thread are created on this class:
while(someCondition){
SomeThread st = new SomeThread();
Thread t = new Thread(st);
t.start();
hashMap.put(unique_id, st)
}
Now, let's suppose the hashMap
is visible to all of the thread created. Can I just access the hashMap
using the unique_id
to get the object of the thread I need and then call st.someMethod()
?
EDIT: I'm asking this question from a P2P network programming perspective. Say a peer is listening for messages from other peers and once it gets a particular message, I need it to send another standard message to all other peers connected to it. In this case, can I just synchronize the method that sends this standard message?
Upvotes: 2
Views: 6278
Reputation: 180161
Code running in any thread can invoke any accessible method on any object to which it has a reference. Of course, the method runs on the thread that invokes it.
But multiple threads accessing the same shared objects must be properly synchronized, else the behavior of the resulting program is not well-defined, and may in practice exhibit all manner of surprising and counter-intuitive characteristics. Synchronization is far too broad a topic to fully address here, but in your example, I would suggest at least
use java.util.concurrent.ConcurrentHashMap
instead of java.util.HashMap
.
ensure that all access to shared state by SomeThread.someMethod()
is properly synchronized, possibly by marking that whole method synchronized
.
Upvotes: 1
Reputation: 140427
It doesn't work like this: threads don't own methods. A thread is nothing but a "sequence of activity".
Calling a method on a thread object will run that method within the same thread that is running the client code which invokes that method.
You should do that differently: one typically approach is that the other thread keeps polling the content of some shared data structure. Normally you would use some sort of queue for that.
Thread A puts some kind of command into a queue and thread B reacts to that at some point.
But please note: such designs are somehow "last decade". Nowadays you rather avoid using bare threads and low level interactions between them. Instead you look into advanced abstractions - such as ExecutorService, Futures,...
Upvotes: 1