首先,该过程只会与最慢的部分一样快。如果时序故障为:
- 枪位: 1 秒
- sed: 5 秒
- 格兹普: 1 秒
通过多线程,您将最多在5秒而不是7秒内完成。
其次,与其使用您正在使用的队列,不如尝试复制要复制的内容的功能,并使用 PipedInputStream
和 PipedOutputStream
将进程链接在一起。
编辑:有几种方法可以使用Java并发实用程序处理相关任务。将其划分为多个线程。首先创建一个公共基类:
public interface Worker {
public run(InputStream in, OutputStream out);
}
此接口的作用是表示处理输入并生成输出的任意作业。把这些链接在一起,你就有了一个管道。您也可以抽象出样板。为此,我们需要一个类:
public class UnitOfWork implements Runnable {
private final InputStream in;
private final OutputStream out;
private final Worker worker;
public UnitOfWork(InputStream in, OutputStream out, Worker worker) {
if (in == null) {
throw new NullPointerException("in is null");
}
if (out == null) {
throw new NullPointerException("out is null");
}
if (worker == null) {
throw new NullPointerException("worker is null");
}
this.in = in;
this.out = out;
this.worker = worker;
}
public final void run() {
worker.run(in, out);
}
}
因此,例如,PART:Unzip
public class Unzip implements Worker {
protected void run(InputStream in, OutputStream out) {
...
}
}
,以此类推,用于 和 。然后,将它绑定在一起的是:Sed
Zip
public static void pipe(InputStream in, OutputStream out, Worker... workers) {
if (workers.length == 0) {
throw new IllegalArgumentException("no workers");
}
OutputStream last = null;
List<UnitOfWork> work = new ArrayList<UnitOfWork>(workers.length);
PipedOutputStream last = null;
for (int i=0; i<workers.length-2; i++) {
PipedOutputStream out = new PipedOutputStream();
work.add(new UnitOfWork(
last == null ? in, new PipedInputStream(last), out, workers[i]);
last = out;
}
work.add(new UnitOfWork(new PipedInputStream(last),
out, workers[workers.length-1);
ExecutorService exec = Executors.newFixedThreadPool(work.size());
for (UnitOfWork w : work) {
exec.submit(w);
}
exec.shutdown();
try {
exec.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedExxception e) {
// do whatever
}
}
我不确定你能做得比这更好,而且每个工作都需要编写最少的代码。然后你的代码变成:
public static processFile(String inputName, String outputName) {
pipe(new FileInputStream(inputFile), new FileOutputStream(outputFile),
new Zip(), new Sed(), new Unzip());
}