假设我有三个不同长度的数组。 我想用三个不同的线程对这三个数组进行排序。
我为此编写了以下代码。是这样写的还是出了什么问题。 有时它给我正确的结果,有时数组的值与其他数组的值合并:
我添加了同步显示方法,再次得到不正确的结果。
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();
}
最佳答案
您的数组的顺序可能是正确的。但打印的结果是交错的,因为打印发生在不同的线程上。
对每个线程上的数组进行排序,然后在所有线程完成后打印所有结果。
关于java - 无法使用线程获得正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30847114/