我应该如何处理 Java 中的多线程? [英] How should I handle Multi-threading in Java?

查看:56
本文介绍了我应该如何处理 Java 中的多线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个与 Java 相关的实际场景;一个套接字程序.现有系统和预期系统如下.

I am working on a practical scenario related with Java;a socket program. The existing system and the expected system are as follows.

现有系统 - 系统检查是否满足特定条件.如果是这样,它将创建一些要发送的消息并将其放入队列中.

Existing System - The system checks that a certain condition is satisfied. If so It will create some message to be sent and put it into a queue.

队列处理器是一个单独的线程.它会定期检查队列中是否存在项目.如果找到任何项目(消息),它只会将消息发送到远程主机(硬编码)并从队列中删除该项目.

The queue processor is a separate thread. It periodically check the queue for existence of items in it. If found any items (messages) it just sends the message to a remote host (hardcoded) and remove the item from queue.

预期系统 - 这就是类似的东西.当满足特定条件时创建消息,但在每种情况下收件人都不相同.所以有很多方法.

Expected System - This is something like that. The message is created when a certain condition is satisfied but in every case the recipient is not same. So there are many approaches.

  1. 将消息放入同一个队列,但带有接收者 ID.在这种情况下,第二个线程可以识别接收方,以便将消息发送给该接收方.

  1. putting the message into the same queue but with its receiver ID. In this case the 2nd thread can identify the receiver so the message can be sent to that.

有多个线程.在这种情况下,当条件满足并且接收方处于新建"状态时,它会创建一个新队列并将消息放入该队列中.一个新线程初始化以处理该队列.如果下一条消息被定向到同一个接收者,它应该放入同一个队列,如果不是一个新队列,则应该创建线程.

Having multiple threads. In this case when the condition is satisfied and if the receiver in "New" it creates a new queue and put the message into that queue. And a new thread initializes to process that queue. If the next messages are directed to same recipient it should put to the same queue and if not a new queue and the thread should be created.

现在我想实现第二个,有点卡住了.我该怎么做?一个骨架就足够了,您无需担心如何创建队列等... :)

Now I want to implement the 2nd one, bit stucked. How should I do that? A skeleton would be sufficient and you won't need to worry to put how to create queues etc... :)

更新:我也认为方法 1 是最好的方法.我阅读了一些关于线程的文章并做出了这个决定.但是学习如何实现方法2也是非常值得的.

Update : I also think that the approach 1 is the best way to do that. I read some articles on threading and came to that decision. But it is really worth to learn how to implement the approach 2 as well.

推荐答案

首先,如果你计划有很多接收器,我不会使用 ONE-THREAD-AND-QUEUE-PER-RECEIVER 方法.您可能最终会遇到很多线程在大多数情况下不做任何事情,而我可能会在整个性能范围内损害您的性能.另一种方法是使用工作线程的线程池,只需从共享队列中挑选任务,每个任务都有自己的接收器 ID,也许还有一个共享字典,其中包含到每个接收器的套接字连接,供工作线程使用.

First of all, if you are planning to have a lot of receivers, I would not use the ONE-THREAD-AND-QUEUE-PER-RECEIVER approach. You could end up with a lot of threads not doing anything most of the time and I could hurt you performance wide. An alternative is using a thread pool of worker threads, just picking tasks from a shared queue, each task with its own receiver ID, and perhaps, a shared dictionary with socket connections to each receiver for the working threads to use.

话虽如此,如果您仍想追求自己的方法,您可以做的是:

Having said so, if you still want to pursue your approach what you could do is:

1) 创建一个新类来处理您的新线程执行:

1) Create a new class to handle your new thread execution:

public class Worker implements Runnable {
   private Queue<String> myQueue = new Queue<String>();
   public void run()
   {
       while (true) {
          string messageToProcess = null;
          synchronized (myQueue) {
             if (!myQueue.empty()) {
                 // get your data from queue
                 messageToProcess = myQueue.pop();
             }
          }
          if (messageToProcess != null) {
             // do your stuff
          }
          Thread.sleep(500); // to avoid spinning
       }
   }
   public void queueMessage(String message)
   {
      synchronized(myQueue) {
         myQueue.add(message);
      }
   }
}

2) 在您的主线程上,创建消息并使用字典(哈希表)查看接收者的线程是否已创建.如果是,则只是将新消息排队.如果没有,则创建一个新线程,将其放入哈希表并将新消息排队:

2) On your main thread, create the messages and use a dictionary (hash table) to see if the receiver's threads is already created. If is is, the just queue the new message. If not, create a new thread, put it in the hashtable and queue the new message:

while (true) {
   String msg = getNewCreatedMessage(); // you get your messages from here
   int id = getNewCreatedMessageId();   // you get your rec's id from here
   Worker w = myHash(id);
   if (w == null) {   // create new Worker thread
      w = new Worker();
      new Thread(w).start();
   }
   w.queueMessage(msg);
}

祝你好运.

您可以使用 BlockingQueue Brian 提到了这种方法.

you can improve this solution by using BlockingQueue Brian mentioned with this approach.

这篇关于我应该如何处理 Java 中的多线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆