且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我应该如何处理 Java 中的多线程?

更新时间:2023-01-12 13:39:04

首先,如果你计划有很多接收器,我不会使用 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.