我是Java新手,我想实现一个byte[]缓冲区,其中一个线程可以写入,另一个线程可以从中读取。
听起来它应该已经在java中实现了,但是我花了几个小时试图找到/理解几个类,我不知道它是否能实现我想要的,以及如何使用它。
我看到BufferedInputStream,ByteBuffer,ByteChannel,BlockingQueue.
有人能指出一个更具体的方向吗?我使用SDK 1.6
发布于 2014-03-12 12:16:51
对不起,ByteBuffer对我不好,因为它涉及到使用缓冲区的position。
我意识到我真正需要的只是一个简单的pipe (我不知道我怎么能忘记管道)。
我举了一个来自这里的例子:
PipedOutputStream output = new PipedOutputStream();
PipedInputStream input = new PipedInputStream(output);发布于 2014-03-11 14:07:25
如果您只想将字节从一个线程流到另一个线程,我建议您使用PipedInputStream和PipedOutputStream。不过,请注意,由于设计错误,您可能处于需要这样的解决方案的位置。
举个例子,下面是你如何做这样的事情:
PipedOutputStream out = new PipedOutputStream();
PipedInputStream in = new PipedInputStream(out);
new YourReadingThread(in).start();
new YourWritingThread(out).start();然后,您写到out的任何东西都可以通过in阅读。
如果您正在寻找使线程安全的ByteBuffer的解决方案,我建议您使用ReentrantReadWriteLock
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
ByteBuffer buffer = ByteBuffer.allocate(n);
// Reading thread:
lock.readLock().lock();
buffer.get(i);
lock.readLock().unlock();
// Writing thread:
lock.writeLock().lock();
buffer.put(b,i);
lock.writeLock().unlock();https://stackoverflow.com/questions/22327727
复制相似问题