I have created a number of threads. I know each threads name(suppose through an alien mechanism I set name of thread.) Now I am inside a thread and want to send a message to another thread.
I am trying to code a simulator of Pastry and Chord protocol. I can not have a number of distributed nodes, so I have created a number of threads. Now I want each thread send and receive messages from one another. I have set each nodes name as its IP(a randomly generated number). Now I do not know how to send a message from one node to another. Please tell me how to send a message from one thread to another if you know another threads name.
I would suggest some kind of a message system. The easiest way would be to create a thread-safe FIFO and pass it into each thread. If you want to send messages directly to each different thread, make a “Topic” for each thread.
Don’t try to hack something in using the thread name, it’ll just constrain you later.
Pasted from comment so I can parse it:
private static BlockingQueue[] queue; private static int queueNum = 0; public static void newQueue(String ip) { queue[queueNum] = new ArrayBlockingQueue(1024); try{ queue[queueNum].put(ip); } catch (InterruptedException e){e.printStackTrace(); } queueNum++; }Oh, I see your problem. You never assign BlockingQueue a value. Try changing that line to:
That will allow you 10 queues.
I’d also suggest that instead of an array you use a HashMap so you can name, add and delete queues at will. Instead of being queue[2] you’ll be addressing queue.get(“Thread1Queue”) or something more descriptive.
Note response to comments:
A HashMap can generally replace an array, it’s lookup is nearly as quick but it uses anything for an index instead of numbers–Strings, enums, Objects, whatever you want (as long as it has the hash and equals methods overriden), but usually strings.
So if you are storing a bunch of queues, and you want to name them specifically, you can say:
HashMap queues=new HashMap(); queues.put("queue1", new ArrayBlockingQueue(1024)); queues.put("queue2",new ArrayBlockingQueue(1024)); ...Then whenever you want to access one you can use:
queues.get("queue1").put(new ThingToAddToArrayBlockingQueue())...to put a “Thing to add” to queue1.
If you just want a “Bunch” of them and don’t need to know which is which (Just a collection of threads that can be fed generic taskss) there are specific collections/patterns for that in the concurrent package.