Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have 2 Threads Talk To Each Other?

I'm currently making a IRC bot in Java (I know, there are frameworks out there) and I'm trying to have it connect to multiple servers. The problem I'm having with this is not the connecting part, I'm just running my Connect class in x amount of threads. Each thread will connect the bot to the server/port specified. Now my problem is that when certain text is outputted by a user the bot is supposed to message the channel saying "you typed this command" (for an example). Now I would want the bot to message ALL servers saying "you typed this command". This is simply just an example (which is why it doesnt make much sense).

Connect f = new Connect(irc.freenode.net, 6667);
Thread ft = new Thread(f);
ft.start();
Connect q = new Connect(irc.quakenet.org, 6667);
Thread qt = new Thread(q);
qt.start();

Now having the example code above, I would want one thread to talk to the other when certain text is typed. Something like:

if (lineReader.substring(lineReader.indexOf(":"), lineReader.length()).equals("hello")) {
    message both servers "Hello World!" 
}

If anyone could help, I'd greatly appreciate it. Thanks!

like image 700
zamN Avatar asked Oct 29 '10 16:10

zamN


2 Answers

I think a simple approach would be an Observer pattern where each thread knows about all the other threads

like image 135
Tommy Avatar answered Oct 29 '22 09:10

Tommy


You should give each thread a Queue of incoming messages that other threads can push to in an asynchronous manner; java.util.concurrent.ConcurrentLinkedQueue would probably be a good class to use for that.

You will then need a single MessageSender class instance that has references to all your threads. If a thread wants to send a message to all other threads, it would call send(msg) on this global MessageSender object, and it in turn will then iterate over all threads and push the message to their respective queues (skipping the thread of the sender).

The threads themselves can then check their own queue from time to time (depending on whatever other logic they may be executing as well) and remove messages once they have handled them.

like image 21
Luke Hutteman Avatar answered Oct 29 '22 10:10

Luke Hutteman