假設你需要處理2個線程,一個Reader
和Processor
工作。Java的多線程,讓線程並行
Reader
將讀取流數據的一部分,並將其傳遞給Processor
,這將做一些事情。
的想法是不是太多數據的強調讀者。
在設立,我
// Processor will pick up data from pipeIn and will place the output in pipeOut
Thread p = new Thread(new Processor(pipeIn, pipeOut));
p.start();
// Reader will pick a bunch of bits from the InputStream and place it to pipeIn
Thread r = new Thread(new Reader(inputStream, pipeIn));
r.start();
不用說,在初始化時沒有管爲空。
我想......當Processor
已啓動它試圖從pipeIn閱讀,在下面的循環:
while (readingShouldContinue) {
Thread.sleep(1); // To avoid tight loop
byte[] justRead = readFrom.getDataCurrentlyInQueue();
writeDataToPipe(processData(justRead));
}
如果沒有數據來寫,會寫什麼,應該是沒問題。
的Reader
開始活躍,並從流拿起一些數據:
while ((in.read(buffer)) != -1) {
// Writes to what processor considers a pipeIn
writeTo.addDataToQueue(buffer);
}
管道本身,我同步訪問數據。
public byte[] getDataCurrentlyInQueue() {
synchronized (q) {
byte[] a = q.peek();
q.clear();
return a;
}
}
我期望2個線程並行半運行,Reader
和Processor
之間交換活動。然而,什麼情況是
- 閱讀器讀取所有塊前面
- 處理器把一切都爲1單塊
我在想什麼嗎?
InputStream.read(byte [])是一個阻止呼叫 – 2012-01-31 02:47:30
@guido嗨guido。有什麼可以推薦我嗎? – JAM 2012-01-31 02:50:29
試着看着java。nio SocketChannel和ByteBuffer類:AH和管道類) – 2012-01-31 02:52:33