简体   繁体   English

Java中如何将子线程的消息返回到主线程(方法)?

[英]How to return messages from child threads to main thread(method) in Java?

I have a HashMap of people who want to communicate with each other as follows:我有一个 HashMap 的人想互相交流如下:

{zidane=[rooney, rooney, rooney, scholes, rooney], rooney=[scholes, messi, scholes], scholes=[ronaldo], ronaldo=[rooney, messi, scholes], messi=[zidane]}

Here, each person in the key will have their own threads in which they will send a message to each person in their list and receive a response.在这里,密钥中的每个人都有自己的线程,他们将在其中向列表中的每个人发送消息并接收响应。

import java.util.*;

public class Master {
    public Map callsMap = new HashMap<String, List>();

    public static void main(String[] args){
        Master m = new Master();
        m.readFile();
        Iterator<Map.Entry<String, List>> it = m.callsMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, List> pair = it.next();
            String caller = pair.getKey();
            List receiverList = pair.getValue();
            SubTasks st = new SubTasks(caller, receiverList);
            Thread thread = new Thread(st);
            thread.start();
            //st.getMessage();
        }
    }
}

The master class will iteratively create a thread for every key in the HashMap. master class 将为 HashMap 中的每个键迭代创建一个线程。 Please note that the readFile method will just read from a text file and produce the input (into callsMap variable) I have mentioned above.请注意, readFile方法只会从文本文件中读取并生成我上面提到的输入(到callsMap变量中)。 It is not particularly important for this context so I have omitted it here.这对于这种情况并不是特别重要,所以我在这里省略了它。

I have the SubTasks class which extends the Thread class and creates messages for each interaction.我有SubTasks扩展了Thread class 并为每个交互创建消息。 This class will not create any additional threads but just operate on the caller and receiver list it received as follows:这个 class 不会创建任何额外的线程,而只是对它收到的调用者和接收者列表进行操作,如下所示:

import java.util.List;

public class SubTasks extends Thread {
    private String caller;
    private List receiverList;
    private volatile String returnMessage;

    SubTasks(String s, List l){
        caller = s;
        receiverList = l;
    }

    public void setMessage(String msg){
        returnMessage = msg;
    }

    public String getMessage() {
        return returnMessage;
    }

    @Override
    public void run(){
        for (int i = 0; i < receiverList.size(); i++) {
            System.out.println(receiverList.get(i)+" received intro message from "+caller +" ["+System.currentTimeMillis()+"]");
            returnMessage = caller+" received reply message from "+receiverList.get(i) +" ["+System.currentTimeMillis()+"]";
            //setMessage(returnMessage);
            System.out.println(returnMessage);
        }
    }
}

I get the desired output if I print the messages in the child threads for all 26 pairs.如果我在子线程中为所有 26 对打印消息,我会得到所需的 output。

zidane received message from messi [1592117172946]
rooney received message from ronaldo [1592117172946]
scholes received message from rooney [1592117172946]
rooney received message from zidane [1592117172946]
ronaldo received message from scholes [1592117172946]
messi received reply from zidane [1592117172989]
ronaldo received reply from rooney [1592117172989]
...
...

How do I pass these messages into the main thread (method) and print it there instead of the child threads?如何将这些消息传递到主线程(方法)并在那里打印而不是子线程? I tried using getter-setter methods but since the threads will execute randomly, there is no way to call the getter methods properly.我尝试使用getter-setter方法,但由于线程将随机执行,因此无法正确调用getter方法。

I would suggest to you to use Executor framework Callable interface and Futures in your usecase, since everything you need is already solve.我建议你在你的用例中使用Executor框架Callable接口和Futures ,因为你需要的一切都已经解决了。 Rewriting the class would help you to solve it properly.重写 class 将帮助您正确解决它。

     public class Master {
        public Map callsMap = new HashMap<String, List>();

            public static void main(String[] args){
                Master m = new Master();
                m.readFile();
                ExecutorService executorService = Executors.newFixedThreadPool(10);// or some desired number
                List<Future<String>> returnFutures = new ArrayList<>();
                Iterator<Map.Entry<String, List>> it = m.callsMap.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, List> pair = it.next();
                    String caller = pair.getKey();
                    List receiverList = pair.getValue();
                    returnFutures.add(executorService.submit(new SubTasks(caller, receiverList) ));
                }
                executorService.shutdown();
                while(executorService.awaitTermination(1000, TimeUnit.SECONDS));
                for(Future<String> returnFuture: returnFutures){
                     /* returnFuture.get() will have the returned value from the thread, if the thread has completed execution, 
                     otherwise it will wait for the completion*/
                    System.out.println(returnFuture.get());

                }
            }
    }

and

    public  class SubTasks implements Callable<String> {
        private String caller;
        private List receiverList;
        private volatile String returnMessage;

        SubTasks(String s, List l){
            caller = s;
            receiverList = l;
        }

        public void setMessage(String msg){
            returnMessage = msg;
        }

        public String getMessage() {
            return returnMessage;
        }

        @Override
        public String call (){
            for (int i = 0; i < receiverList.size(); i++) {
                System.out.println(receiverList.get(i)+" received intro message from "+caller +" ["+System.currentTimeMillis()+"]");
                returnMessage = caller+" received reply message from "+receiverList.get(i) +" ["+System.currentTimeMillis()+"]";
                return returnMessage;
            }
        }
    }

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

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