线程间消息实现 [英] Inter-thread messaging implementation

查看:31
本文介绍了线程间消息实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是让一个线程将从其父线程接收到的消息写入 OutputStream,监听 InputStream 以获取回复,然后将回复通知父线程.我写了两个测试类,它们以不同的方式做类似但更简单的事情.方法 1 仅在 "before loop" 调试语句未注释时有效,方法 2 仅打印 "message from child" 调试语句.我做错了什么?

What I'm trying to do is have a thread write a message it received from its parent thread to an OutputStream, listen to an InputStream for the reply and then notify the parent thread with the reply. I wrote two test classes that do something similar but simpler in different ways. Method 1 only works when the "before loop" debug statement is uncommented, method 2 only prints the "message from child" debug statements. What am I doing wrong?

方法一

public class Parent {
    private static int out = 0;
    private static int in = 0;

    public static void main(String[] args) {
        final Object locker = new Object();
        Thread t = new Thread(new Runnable() {          
            @Override
            public void run() {
                while (true) {
                    synchronized (locker) {
                        try {
                            locker.wait();
                            System.out.println("Message from parent " + out);
                            in = out + 10;
                            locker.notify();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        t.start();

        System.out.println("before loop");
        while (out < 10) {
            synchronized (locker) {
                locker.notify();
                try {
                    locker.wait();
                    out++;
                    System.out.println("Message from child " + in);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }               
            }   
        }       
    }
}

方法二

public class Parent {

    /**
     * @param args
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws InterruptedException {
        final BlockingQueue<Integer> q = new ArrayBlockingQueue<Integer>(1);

        Thread t = new Thread(new Runnable() {          
            @Override
            public void run() {
                while (true) {
                    try {
                        Integer i = q.take();               
                        System.out.println("Message from parent: " + i.intValue());
                        q.put(i.intValue() + 10);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }               
            }
        });

        for (int i = 0; i < 10; i++) {
            q.put(i);
            Integer j =  q.take();
            System.out.println("Message from child: " + j);
        }
    }

}

推荐答案

Java API 已经提供了该功能;你有充分的理由重新发明轮子吗?

The Java API already offers that functionality; do you have a valid reason to reinvent the wheel?

public static void main(String[] args) throws Exception {
    // start a worker thread
    ExecutorService exec = Executors.newFixedThreadPool(1);

    // ask the worker thread to execute a task (
    Future<String> future = exec.submit(() -> {
        Thread.sleep(500); // simulate waiting for I/O
        return "hello from child";
    });

    // get the return value from the worker thread (waiting until it is available)
    String greeting = future.get();
    System.out.println(greeting);

    // terminate the worker thread (otherwise, the thread will wait for more work)
    exec.shutdown();
}

这篇关于线程间消息实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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