假设我有三个不同长度的数组。 我想用三个不同的线程对这三个数组进行排序。
我为此写了下面的代码。所以它是写的还是有些事情发生了错误。 有时它给我正确的结果,有时数组的值与其他数组的值合并:
我添加了同步到显示方法,再次得到错误的结果。
public class ThreadDemo implements Runnable {
private int[] arr;
private String[] s_arr;
public ThreadDemo(int arr[]) {
this.arr=arr;
}
@Override
public void run() {
getSorted(arr);
try{
Thread.sleep(2000);
}catch(InterruptedException e){
e.printStackTrace();
}
}
private void getSorted(int[] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < (arr.length-1) - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
display(arr);
}
public static void display(int[] a){
for(int i:a)
System.out.print(i+" ");
System.out.println();
}
public static void main(String[] args) {
int arr1[]={8,25,9,12,13,17,1};
int arr2[]={38,2,19,12,3,17,16};
int arr3[]={3,22,9,1,34,17,86};
ThreadDemo demo1=new ThreadDemo(arr1);
Thread t1=new Thread(demo1);
ThreadDemo demo2=new ThreadDemo(arr2);
Thread t2=new Thread(demo2);
ThreadDemo demo3=new ThreadDemo(arr3);
Thread t3=new Thread(demo3);
t1.start();
t2.start();
t3.start();
}
}
输出#1:这里的值正在混合。
1 8 9 12 13 17 25
2 3 12 16 17 1 3 9 17 22 34 86
19 38
输出#2:正确
1 8 9 12 13 17 25
2 3 12 16 17 19 38
1 3 9 17 22 34 86
输出#3:不正确
1 8 9 12 13 17 25
2 1 3 3 12 9 16 17 17 22 19 38
34 86
public static synchronized void display(int[] a){
for(int i:a)
System.out.print(i+" ");
System.out.println();
}
答案 0 :(得分:2)
Your arrays are probably in the correct order. But the printed results are being interleaved because the prints are happening on different threads.
Sort the arrays on each thread and then print all the results once all threads have finished.