我正在尝试创建一个Piped I / O mergesort。我有分拣工作,但我正在努力合并管道。
这是我的Merger.java
1 import java.util.*;
2 import java.io.*;
3 class Merger implements Runnable {
4
5 ObjectInputStream ins[] = new ObjectInputStream[2];
6 ObjectOutputStream out = null;
7 int b[] = null, start=0;
8 //1 level merger, we do other 4 levels
9 //Only last level need an array to write into it
10 public Merger ( PipedInputStream in1, PipedInputStream in2, PipedOutputStream pout, int b[]) {
11 try {
12 ins[0] = new ObjectInputStream(in1);
13 ins[1] = new ObjectInputStream(in2);
14 if(pout==null) {
15 System.out.println("POUT = NULL\n");
16 out = null;
17 }
18 else{
19 out = new ObjectOutputStream(pout);
20 }
21 this.b = b;
22 } catch (Exception e) {}
23 }
24
25 public void run() {
26 int num[] = { -1, -2 },
27 errCnt=0, // number of pipes caused error
28 k = -1; // k will be 0 or 2 indicating the pipe to read from
29
30 try {
31 num[0] = ins[0].readInt(); // read from first pipe
32 num[1] = ins[1].readInt(); // read from second pipe
33 } catch (IOException e ) {
34 System.out.printf("\n\t\tOne or two pipes are not connected.\n");
35 return;
36 }
37
38 //compares num[0] & num[1], k written to array
39 while(errCnt < 2) {
40 try {
41 if( errCnt < 1 ) k = num[0] <= num[1] ? 0 : 1;
42
43 if( b != null) b[start++] = num[k];
44 else {
45 out.write(num[k]);
46 out.flush();
47 }
48 num[k] = ins[k].readInt();
49 } catch( IOException e ) {
50 errCnt++;
51 //find source of exception
52 k = ( k == 0 ? 1 : 0);
53 }
54 }
55 }
56
57 }
我在两种不同的情况下调用此函数。我有6种不同的合并级别。 0 - 5.在1-4上我打电话
122 for(int i = level-1; i >= 0; i--){
123 n = (int) Math.pow(2,i-1);
124 for(int j = 0; j < n; j++){
125 if (i == 1){
126 mergers[i-1][j] = new Merger(pin[i][j*2], pin[i][j*2+1], null, b);
127 System.out.printf("Merger[%d][%d] (pin[%d][%d], pin[%d][%d], null, b\n", i-1, j, i , j*2 , i, j*2+1);
128 }
129 else {
130 mergers[i-1][j] = new Merger(pin[i-1][i*2], pin[i-1][i*2+1], pout[i-1][j], null);
131 System.out.printf("Merger[%d][%d] (pin[%d][%d], pin[%d][%d], pout[%d][%d], null\n", i-1, j, i , j*2 , i, j*2+1, i-1, j);
132 }
133
134 }
135 }
我在第126和130行得到错误。我认为这是因为在最后一级我将null传递给Pipedoutput(pout)而其他级别我将null传递给数组b。
打印语句只是调试我传递的正确值