我可以为多线程使用PipedOutputStream吗?

3

我能否使用一个PipedOutputStream为多线程服务并将其连接到一个PipedInputStream,然后从多个线程中获取所有的输出?

以下是代码片段,我的目标是修改和删除线程的输出可用于同步线程,但删除线程的输出被遗漏了。请在最后列出P4Thread的run()方法。

PipedInputStream input = new PipedInputStream();
PipedOutputStream output = new PipedOutputStream();

input.connect(output);

P4Thread syncthread = new P4Thread (new String[]{p4exe, "-x-", "sync", "-f"},input, out);
P4Thread modifythread = new P4Thread (new String[]{p4exe, "diff", "-se"},new ClosedInputStream(), output);
P4Thread deletethread = new P4Thread (new String[]{p4exe, "diff", "-sd"},new ClosedInputStream(), output);  

try {
    syncthread.start();
    modifythread.run();
    output.flush();

    deletethread.run();
    output.flush();
    output.close();

    syncthread .join();
    } catch (InterruptedException e) {
        syncthread .interrupt();
    }

public void run() { 
Launcher.ProcStarter ps = new Launcher.LocalLauncher(listener).launch(); 
ps.envs(env).stdin(input).stdout(output).cmds(cmdList); 
if (workDir != null) { 
    ps.pwd(workDir); 
}
try{
   ps.join();
   }catch (InterruptedException e) {
            if (output != null && closePipes) {
                IOUtils.closeQuietly(output);
            }
            //return -1;
        } catch (IOException e) {
            if (output != null && closePipes) {
                IOUtils.closeQuietly(output);
            }
        } finally {
            if (closePipes) {
                IOUtils.closeQuietly(input);
                IOUtils.closeQuietly(output);
            }
        }
}
1个回答

2

可以的,只要你确保同步你的多线程写操作,使它们不会交错。


我更新了问题并附上了代码片段。我执行了flush和close操作。看起来deletethread的输出被忽略了。 - hotnwwp
@hotnwwp 现在我真的不明白了。为什么要启动一个线程并立即加入(join)它?你可能只需调用它的run()方法就可以了。 - user207421
@hotnwwp,你在modifythread.start();后面立即跟着modifythread.join();。这与modifythread.run()完全等效,只是浪费了一个线程。对于deletethread也是一样的,.start()/join() - user207421
我确实从modifythread得到了结果,所以我不认为它浪费了一个线程。我这样写是因为我希望在modifythread完成后再运行deletethread。 - hotnwwp
@hotnwwp 我并没有说你不会得到结果。当然,你会得到结果。它会运行。只需调用run()方法,你也将获得结果。尝试一下。你可以通过调用modifythread.run()然后deletethread.run()来获得顺序执行。你让这个问题变得比实际上更复杂了。 - user207421
显示剩余14条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接