如何创建单独的输出行,具体取决于输出来自哪个线程?

时间:2013-04-05 12:01:54

标签: java arrays multithreading sorting io

我有一个实现两种不同排序算法的程序。我通过在不同的线程中启动它们来并行测试两种算法。我希望能够在每个线程中查看排序操作的结果,并尝试将这些结果保存在同一行(对于每个线程)。

  

例如:

      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();
    }
}

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

2 个答案:

答案 0 :(得分:2)

尝试创建一个同步静态方法只是为了打印数组,因此完成其作业的第一个线程获取锁定并仅在打印整个数组时释放它。

答案 1 :(得分:1)

为什么不在单独的列而不是行中打印:

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

这将更容易实现,只需在新行上打印每个结果,并根据排序算法调整缩进。