Java NIO Pipe和ByteBuffer

时间:2014-02-17 09:50:14

标签: java bytebuffer

我正在尝试将pipe线程(ByteBuffer)中的某些IO1转换为另一个(IO2)。

http://tutorials.jenkov.com/java-nio/pipe.html

private int bufferSize;
private boolean isRecording;

private Thread IO1;
private Thread IO2;

private ByteBuffer byteBuffer1;
private ByteBuffer byteBuffer2;

private Pipe pipe;
private Pipe.SinkChannel skChannel;
private Pipe.SourceChannel sourceChannel;

            byteBuffer1 = ByteBuffer.allocateDirect(bufferSize);
            byteBuffer2 = ByteBuffer.allocateDirect(bufferSize);

            //An instance of Pipe is created
            try
            {
                pipe = Pipe.open();
                skChannel = pipe.sink();
                sourceChannel = pipe.source();

                IO1.start();
                IO2.start();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }

-

IO1 = new Thread(new Runnable()
{
    public void run()
    {
        isRecording = true;
        recorder.startRecording();
        try
        {
            int read;
            while (isRecording)
            {
               // byteBuffer1.clear();
                read = recorder.read(byteBuffer1, bufferSize);
                if (AudioRecord.ERROR_INVALID_OPERATION != read)
                {
                       skChannel.write(byteBuffer1);
                       Log.v("========IO1 ", String.valueOf(read));
                       //This triggered almost 20 times/second
                }
            }
            recorder.stop();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
});

skChannel.write(byteBuffer1);和                        Log.v("========IO1 ", String.valueOf(read));                        触发几乎20次/秒,这是预期的行为,到目前为止一直很好。

IO2 = new Thread(new Runnable()
{
    public void run()
    { 
        try
        {
            int read;
            while (  (read =sourceChannel.read(byteBuffer2)) >0)
            {
                Log.v("========IO2 ", String.valueOf(read));
                //this triggered only once

                // To do Codec etc.
                //............
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        } 
        Log.v("========IO2 ", "END!!!!!"); //never triggered(this is fine)
    }
});

但是,Log.v("========IO2 ", String.valueOf(read));只触发一次,我不知道为什么。

有人可以告诉我如何在IO1中获取线程IO2的更新?

感谢。

1 个答案:

答案 0 :(得分:0)

你需要在写入之前翻转()缓冲区,然后压缩()它。

但是:总之,不要。线程之间的管道基本上没有意义。使用队列,或让接收线程直接读取发送线程的输入。

如果必须这样做,基本的NIO复制循环如下:

while (in.read(buffer) > 0 || buffer.position() > 0) // or whatever your read API needs
{
    buffer.flip();
    out.write(buffer);
    buffer.compact();
}