6

I want to be able to create multiple threads and send data to a specific thread based on what the main program receives.

Basically I am sending a packet to a receiving program which will contain a number. This number is used to determine which thread it wants to communicate with. How can I send that packet to a thread with that same number?

Example: threads 1,2,3,4 and 5 exist. My main program receives a packet with the number 3. I want to send that packet to thread 3.

How can I achieve this?

2
  • Why don't you keep connection alive then entrust data sent/received to the thread containing that socket? Commented Nov 29, 2011 at 2:40
  • I am making a virtual router (a class project) so it needs to act like a real router. So these threads I am making are acting as different ports for my router. Our packets are being sent to the real port that our program is listening to and our program then sends it to a virtual port(thread). Commented Nov 29, 2011 at 2:56

1 Answer 1

6

Create a queue for each thread, and have each thread listen to that queue. Your main thread can then put data (or a "message") on each queue.

You'll just want to make sure that the queue structure you choose is safe for concurrent access (thread-safe). Something like a LinkedBlockingQueue should do nicely.

Sign up to request clarification or add additional context in comments.

3 Comments

I like it! Are the queues created in main thread or in the child threads or both?
Wherever you wish, though I'd create them along with the creation of each thread - which would mean that they are created in the main thread. They're then accessed by both the main and the child threads, with the main thread pushing data on to the queue, and the child threads pulling data off the queue.
Here is an example of the producer-consumer pattern using BlockingQueues. javamex.com/tutorials/synchronization_producer_consumer_2.shtml

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.