I want to make a thread which will sort an array with the BubbleSort method, but I have some problems.
This is my BubbleSort class:
package thread;
import java.util.Arrays;
public class BubbleSort implements Runnable {
private int[] array;
private long start, end;
public BubbleSort(int[] array){
this.array=array;
}
public void sort(){
int j;
boolean flag = true;
int temp;
while (flag) {
flag= false;
for( j=0;j<array.length-1;j++ ){
if (array[j]>array[j+1]){
temp = array[ j ];
array[j] = array[ j+1 ];
array[j+1] = temp;
flag=true;
}
}
}
}
@Override
public void run() {
start = System.currentTimeMillis();
this.sort();
end = System.currentTimeMillis();
System.out.println(end-start);
}
public long getTime(){
return end - start;
}
@Override
public String toString(){
return Arrays.toString(array);
}
}
and the main class:
package multisort;
import thread.BubbleSort;
public class MultiSort {
public static void main(String[] args) {
int[] x = {12,34,53,1,23,532,102,31,12,0,344,123,5422,12341,22,3410,123,342,233,12342,234432,12334};
BubbleSort bs = new BubbleSort(x);
Thread bsThread = new Thread(bs);
bsThread.start();
System.out.println(bs+"\n"+bs.getTime());
/*
bs.sort();
System.out.println(bs); it works
*/
}
}
The problem is that the array will not be sorted if I call my sort method in the run method. Who can help me with a response?
答案 0 :(得分:1)
您不必等待线程完成排序。无论其他线程在做什么,你只需要踩踏数组!
这就像告诉你的女儿她可以使用汽车然后打开引擎盖并取出电机的一些部分。