我正在尝试用PipedInputStream&实现一个线程循环缓冲区。 PipedOutputStream但是每当我在Decoder runnable中找到mHead.write时它都会锁定。我认为在使用单独的线程时没有机会死锁。
private class DecoderTask implements Runnable{
@Override
public void run() {
while(!mStop){
try {
Log.d(TAG,"trying to write");
mHead.write(decode( 0, 1000));
mHead.flush();
Log.d(TAG,"Decoded");
} catch (DecoderException e) {
Log.e(TAG,e.toString());
} catch (IOException e) {
Log.e(TAG,e.toString());
}
}
}
}
private class WriteTask implements Runnable{
@Override
public void run() {
while(!mStop){
try {
Log.d(TAG,"trying to read");
int read = mTail.read(mByteSlave, 0, mByteSlave.length);
mAudioTrack.flush();
mAudioTrack.write(mByteSlave,0,read);
Log.d(TAG,"read");
} catch (IOException e) {
Log.e(TAG,e.toString());
}
}
}
}
//in some function
mTail = new PipedInputStream();
mHead = new PipedOutputStream(mTail);
mByteSlave = new byte[BUF];
mT1 = new Thread(new DecoderTask(), "Reader");
mT2 = new Thread(new WriteTask(), "Writer");
mT1.start();
mT2.start();
return;
编辑:这是我的服务的完整来源http://pastie.org/1179792
logcat打印出来:
试图阅读
试着写
答案 0 :(得分:4)
我遇到了同样的问题,并通过覆盖PIPE_SIZE构造函数中的默认PipedInputStream(int)来解决它。方法PipedOutputStream.write(byte[], int, int)将阻塞,直到所有字节都写入输出流。这可能是默认PIPE_SIZE的问题。
毕竟,尺寸确实重要; - )
答案 1 :(得分:0)
程序没有阻止,它只是非常非常慢和低效。它使用100%的CPU。问题是if (mTail.available() >= mByteSlave.length)
- 在大多数情况下这将返回false,因此您在此线程中获得了一个繁忙的循环。如果你能摆脱这个,那就去做吧。然后这个问题就解决了。如果你做不到,那就变得更复杂......
还有另一个问题:PipedInputStream.read
返回一个int。你需要使用:
int len = mTail.read(mByteSlave, 0, mByteSlave.length);
mAudioTrack.write(mByteSlave, 0, len);
除此之外,我在这段代码中找不到任何错误。我的完整测试用例如下所示:
import java.io.*;
public class Test2 {
PipedOutputStream mHead;
PipedInputStream mTail;
byte[] mByteSlave = new byte[1024];
boolean mStop;
public static void main(String... ar) throws Exception {
new Test2().run();
}
void run() throws Exception {
mTail = new PipedInputStream();
mHead = new PipedOutputStream(mTail);
Thread mT1 = new Thread(new DecoderTask(), "Reader");
Thread mT2 = new Thread(new WriteTask(), "Writer");
mT1.start();
mT2.start();
}
class DecoderTask implements Runnable {
public void run() {
while (!mStop) {
try {
mHead.write(new byte[3000]);
mHead.flush();
System.out.println("decoded 3000");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class WriteTask implements Runnable {
public void run() {
while (!mStop) {
try {
int len = mTail.read(mByteSlave, 0, mByteSlave.length);
if (len < 0) break; // EOF
// mAudioTrack.write(mByteSlave, 0, len);
// mAudioTrack.flush();
System.out.println("written " + len);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
答案 2 :(得分:0)
摆脱涉及available()的测试。无论如何,读取将被阻止,当没有数据时你没有更好的事情。