javanio:两个线程之间的数据交换

yr9zkbsy  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(267)

我想使用javanio实现两个线程之间的数据交换。这是我的密码:
测试.java

public class Test {
    final static int BUFSIZE = 40;
    private static Handler handler = new Handler();
    public static void main(String[] args) throws  Exception {
        final Pipe pipe = Pipe.open();
        new Thread(() -> {
            ReadableByteChannel dst = pipe.source();
            ByteBuffer buffer = ByteBuffer.allocate(BUFSIZE);
            while (true) {
                try {
                    while (dst.read(buffer) >= 0) {
                        buffer.flip();
                        String s = "";
                        while (buffer.remaining() > 0)
                            s = s + new String(new byte[]{buffer.get()});
                        buffer.clear();
                        System.out.println(s);
                    }
                } catch (IOException ioe) {
                    System.err.println(ioe.getMessage());
                }
            }
        }).start();

        PackListener pl = packet -> {
            WritableByteChannel src = pipe.sink();
            ByteBuffer buffer = ByteBuffer.allocate(BUFSIZE);
            buffer.clear();
            buffer.put(packet.getBytes());
            buffer.flip();
            while (src.write(buffer) > 0) ;
            src.close();
        };
          for (int i = 0; i < 3; i++) {
            handler.execInterface(pl);
        }
    }
}

packlistener.java文件

public interface PackListener {
    void doSmth(String packet);
}

处理程序.java

public class Handler {
    public void  execInterface(PackListener pl) {
        String packet = "Hello:" + LocalDateTime.now().toString();
        pl.doSmth(packet);
    }
}

我期待三次:

Hello:2020-08-21T23:42:53.056
Hello:2020-08-21T23:42:53.057
Hello:2020-08-21T23:42:53.058

但我得到了:

Hello:2020-08-21T23:42:53.056
null
null

我在新的线程体中尝试了“while(true)”,但结果是一样的。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题