简体   繁体   English

Java多线程消息传递

[英]Java Multi thread messaging

I have an app with two threads, 1 that writes to a queue and the second one that read async from it. 我有一个具有两个线程的应用程序,一个线程写入队列,第二个线程从队列读取异步。 I need to create a third one that generate 20 more. 我需要创建第三个生成20个以上的代码。 the newly created threads will run till explicitly stopped. 新创建的线程将一直运行到明确停止为止。 those 20 threads should get "live" data in order to analyze it. 那20个线程应该获取“实时”数据以便进行分析。 each of the 20 has a unique ID/name. 20个中的每个都有唯一的ID /名称。 I need to send the relevant data (that the READ thread collect) to the correct thread (of the 20 threads). 我需要将相关数据(READ线程收集的)发送到正确的线程(20个线程中)。 eg if the data include a string with id (in it) of 2 --> I need to send it to thread with the ID =2. 例如,如果数据包含ID(在其中)为2的字符串->我需要将其发送到ID = 2的线程。 my question is: how should I hold a "pointer" to each of the 20 threads and send it the relevant data? 我的问题是:我应该如何为20个线程中的每个线程持有一个“指针”并向其发送相关数据? (I can search the id in a runnable list (that will hold the threads)--> but then I need to call to a method "NewData(string)" in order to send the data to the running thread). (我可以在可运行列表(将保存线程)中搜索ID,但是我需要调用方法“ NewData(string)”以将数据发送到正在运行的线程)。 How should I do it? 我该怎么办? TIA Paz TIA Paz

You would probably be better to use a Queue to communicate with your threads. 使用队列与线程通信可能会更好。 You could then put all of the queues in a map for easy access. 然后,您可以将所有队列放在地图中,以方便访问。 I would recommend a BlockingQueue . 我建议使用BlockingQueue

public class Test {
  // Special stop message to tell the worker to stop.
  public static final Message Stop = new Message("Stop!");

  static class Message {
    final String msg;

    // A message to a worker.
    public Message(String msg) {
      this.msg = msg;
    }

    public String toString() {
      return msg;
    }

  }

  class Worker implements Runnable {
    private volatile boolean stop = false;
    private final BlockingQueue<Message> workQueue;

    public Worker(BlockingQueue<Message> workQueue) {
      this.workQueue = workQueue;
    }

    @Override
    public void run() {
      while (!stop) {
        try {
          Message msg = workQueue.poll(10, TimeUnit.SECONDS);
          // Handle the message ...

          System.out.println("Worker " + Thread.currentThread().getName() + " got message " + msg);
          // Is it my special stop message.
          if (msg == Stop) {
            stop = true;
          }
        } catch (InterruptedException ex) {
          // Just stop on interrupt.
          stop = true;
        }
      }
    }
  }

  Map<Integer, BlockingQueue<Message>> queues = new HashMap<>();

  public void test() throws InterruptedException {
    // Keep track of my threads.
    List<Thread> threads = new ArrayList<>();
    for (int i = 0; i < 20; i++) {
      // Make the queue for it.
      BlockingQueue<Message> queue = new ArrayBlockingQueue(10);
      // Build its thread, handing it the queue to use.
      Thread thread = new Thread(new Worker(queue), "Worker-" + i);
      threads.add(thread);
      // Store the queue in the map.
      queues.put(i, queue);
      // Start the process.
      thread.start();
    }

    // Test one.
    queues.get(5).put(new Message("Hello"));

    // Close down.
    for (BlockingQueue<Message> q : queues.values()) {
      // Stop each queue.
      q.put(Stop);
    }

    // Join all threads to wait for them to finish.
    for (Thread t : threads) {
      t.join();
    }
  }

  public static void main(String args[]) {
    try {
      new Test().test();
    } catch (Throwable t) {
      t.printStackTrace(System.err);
    }
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM