Dave's Brain

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 }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.