我有一个实现两种不同排序算法的程序。我通过在单独的线程中启动它们来并行测试这两种算法。我希望能够查看排序操作的结果,因为它们发生在每个线程中,并试图将这些结果保持在同一行(对于每个线程)。
例如:
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();
}
}
任何帮助或指导表示赞赏,谢谢。