Communicating between two threads

You could have a BlockingQueue of message objects. Other threads would place messages onto the queue. As part of the while(true) loop, thread A would poll the queue and process any messages that have arrived.

In code:

class A extends Thread{
 List<Object>  objs = something ;//init it
 BlockingQueue<Message> queue = new LinkedBlockingQueue<Message>();
 void run(){
     while(true){
       Message msg;
       while ((msg = queue.poll()) != null) {
         // process msg
       }
       // do other stuff
     }
   }
}

Other threads can now call queue.put() to send messages to thread A.

Leave a Comment