Date: 2015nov10
Update: 2025oct9
Language: Java
Q. Java: Best way to send a message to a thread
A. Use a LinkedBlockingQueue as shown in this full example:
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.lang.InterruptedException;
class Demo {
// Declare a queue outside the thread
public static LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>();
static class MyWonderfulThread extends Thread {
@Override public void run() {
System.out.println("Thread: Start");
boolean keepGoing = true;
while (keepGoing) {
// ... Do things...
// Check for a message
try {
String msg = queue.poll(10, TimeUnit.MILLISECONDS);
if (msg == null) {
msg = "";
}
if (msg.length() > 0) {
System.out.println("Thread: Got msg=" + msg);
}
if (msg.equals("stop")) {
keepGoing = false;
}
}
catch (InterruptedException ex) {
// Ignore
}
}
System.out.println("Thread: Ending");
}
}
// Helper
static void sleepSeconds(final int seconds) {
try {
Thread.sleep(seconds * 1000);
}
catch (InterruptedException ex) {
// Ignore
}
}
public static void main(String []args) {
MyWonderfulThread thread = new MyWonderfulThread();
thread.start();
System.out.println("Main: Start");
sleepSeconds(5);
System.out.println("Main: Sending stop request");
queue.add("stop"); // Send to thread
sleepSeconds(5);
System.out.println("Main: Ending");
}
}
Output:
Main: Start
Thread: Start
... pause ...
Main: Sending stop request
Thread: Got msg=stop
Thread: Ending
... pause ...
Main: Ending