Browse - Programming Tips - Whats the best way to send a mesage to a thread?

Date: 2015nov10
Language: Java

Q.  Whats the best way to send a mesage to a thread?

A.  Use a LinkedBlockingQueue.

import java.util.concurrent.LinkedBlockingQueue; // Declare a queue outside the thread LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(); // Outside the thread, post to the queue queue.add("hello"); // Inside the thread, check for messages for (;;) { // ... do things... // Check for a message String msg = queue.poll(10, TimeUnit.MILLISECONDS); // progress the message }