Somewhere you will need a List
of your Runnables
s like:
List<MyRunnable> runningThreads;
Then you will have an implementation of Runnable
:
class MyRunnable implements Runnable {
public void run() { ... }
}
Now you need to have some way of sending a message to that Runnable
.
class MyRunnable implements Runnable {
public void run() { ... }
public void sendMessage( String message ){ ... }
}
So to send all the runnable a message it's as easy as:
for( MyRunnable runnable : runningThreads ){
sendMessage( "Hello There!" );
}
What to do now depends heavily on what you want to do next with the message. In any way it has to appear somehow in the Thread's visible range. So for starters lets save it in a variable:
class MyRunnable implements Runnable {
private volatile String myLastMessage;
public void run() { ... }
public void sendMessage( String message ){
this.myLastMessage = message;
}
so if you're run
is already run periodically you can get off with:
public void run(){
while( true ){
Thread.sleep( 1000 ); //1s
if( lastMessage != null ){
doSomethingWith( lastMessage );
lastMessage = null;
}
}
}
If you need more than one message stored in the Thread you can use e.g. SynchronizedList
for this.
If you need your Thread to react instantly on the message it received then use a monitor and
notifyAll
method. See e.g. here: http://www.programcreek.com/2009/02/notify-and-wait-example/