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!


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.


我认为一个简单的方法是Observer模式,其中每个线程都知道所有其他线程


messagePasser解决方案将无法工作,因为java中的字符串对象是按值传递的,而不是通过引用传递的。

链接地址: http://www.djcxy.com/p/48490.html

上一篇: 如何分析组合python和c代码

下一篇: 如何让2个线程互相交谈?