2013-04-05 31 views
-5

我有一个程序,实现两种不同的排序算法。我通过在不同的线程中启动它们来并行测试两种算法。我希望能够查看排序操作的结果,因为它们发生在每个线程中,并且试图将这些结果保留在同一行(针对每个线程)。如何创建单独的输出行,取决于输出来自的线程?

例:

ARR1 = 3 5 8 11 16 ...(从线程1输出排序)
ARR2 = 4 7 9 10 17 ...

(从螺纹2输出排序)

在主逻辑运行后,我已经用Thread.sleep(xxx)完成了这个工作,但是这只在我只有一个线程时才起作用。如果我把这个延迟两个线程它显示是这样的:

ARR1 =
ARR2 = ARR1 [I] ARR2 [I] ARR1 [I + 1] ARR2 [I + 2] ...

换句话说,两种排序的输出都显示在同一行上。

这里是我的代码:

import java.util.PriorityQueue; 

class sortareBubbleSort extends Thread { 
    int nre, min, max; 

    public sortareBubbleSort(int nre, int min, int max) { 
     this.nre = nre; 
     this.min = min; 
     this.max = max; 
    } 

    public void run() { 
     int[] x = new int[nre]; 
     for (int i = 0; i < x.length - 1; i++) 
      x[i] = min + (int) (Math.random() * ((max - min) + 1)); 
     boolean doMore = true; 
     while (doMore) { 
      doMore = false; 
      for (int i = 0; i < x.length - 1; i++) { 
       if (x[i] > x[i + 1]) { 
        int temp = x[i]; 
        x[i] = x[i + 1]; 
        x[i + 1] = temp; 
        doMore = true; 

       } 
      } 
     } 

     System.out.println("\nHere is the sorted array with BubbleSort:"); 
     for (int i = 0; i < x.length; i++) 
      System.out.print(x[i] + " "); 
     System.out.print("\n"); 

    } 
} 

class sortareHeapSort extends Thread { 
    int nre, min, max; 

    public sortareHeapSort(int nre, int min, int max) { 
     this.nre = nre; 
     this.min = min; 
     this.max = max; 
    } 

    public void run() { 
     int[] x = new int[nre]; 
     for (int i = 0; i < x.length - 1; i++) 
      x[i] = min + (int) (Math.random() * ((max - min) + 1)); 

     PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>(); 
     for (int w : x) 
      pQueue.add(w); 
     for (int k = 0; k < x.length; k++) 
      x[k] = pQueue.poll(); 

     // Print the array 
     System.out.println("\nHere is the sorted array with HeapSort:"); 
     for (int w : x) 
      System.out.print(w + " "); 
    } 
} 

public class TestThread { 
    public static void main(String args[]) { 
     sortareBubbleSort fir1; 
     sortareHeapSort fir2; 
     fir1 = new sortareBubbleSort(10, 1, 100); 
     fir2 = new sortareHeapSort(10, 100, 200); 
     fir1.start(); 
     fir2.start(); 
    } 
} 

任何帮助或指导赞赏,感谢。

+0

@ Mr.Cool我认为,他的确有其他意义。 – Adrian 2013-04-05 12:10:07

+0

将整个输出构建为一个字符串,并使用某个记录器(例如带有Logback的Slf4J)让它打印。 – Adrian 2013-04-05 12:11:15

+1

不幸的是,您无法控制典型的控制台设备。你将不得不实现你自己的'输出'控制台,它知道线程源,并可以将它们各自的输出分离为专用的'行'。我质疑这样做的重要性,与实施它所需的努力有关。 – Perception 2013-04-05 12:12:45

回答

2

尝试创建一个同步静态方法来打印数组,因此完成其作业的第一个线程获取该锁并仅在打印整个数组时才将其释放。

1

你为什么不单独列打印,而不是行:

Bubblesort Heapsort 
3    
       4 
5    
8 
       7 
11    
       9 
16 
       10 
       17 

这将是更容易实现,只是打印上新的一行中的结果和调整取决于排序算法的压痕。