我在java中自学多线程。我的虚拟示例是我有一大堆我想要排序的记录(一个2D数组)。单线程方法是使用循环遍历记录列表和排序。我想用多线程程序对固定数量的线程进行排序,在这种情况下,2.一个线程将对列表的前半部分进行排序,第二个线程将对剩下的一半进行排序。然后我想输出现在排序的记录列表的结果。如何在java中使用多线程对记录列表进行排序?
如何创建一个工作线程池并对记录列表进行排序?我需要担心data
是共享资源吗?如何将每个线程的结果返回到原始记录列表?以下是我的代码。
import java.util.*;
class RunnableProcess implements Runnable {
private int[] data;
public RunnableProcess(int[] data) {
this.data = data;
}
public void run() {
try {
// sort the records this thread has access to
for (int i = 0; i < data.length; i++) {
Arrays.sort(data[i]);
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
class BigData {
static int[][] data = new int[1000][1000];
public static void main(String [] args) {
// Create records
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[0].length; j++) {
data[i][j] = new Random().nextInt(999);
}
}
// Call on two threads to sort the data variable
// ExecutorService executor = Executors.newFixedThreadPool(2);
// Python type of idea: Pass half the records to each thread and start
// java doesn't support this so what is the java way of doing this?
// Thread thread = new Thread(new RunnableProcess(data[:499]));
// thread.start();
// Thread thread = new Thread(new RunnableProcess(data[499:]));
// thread.start();
}
}
我很乐意提供解决此问题的最佳方法。
查看'ArrayList'和['ArrayList <> #subList()'](https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#subList(int ,%20int)) – AJNeufeld
你已经忘记了你需要做的第三步 - 合并排序后的结果。看看合并排序算法! –