【发布时间】:2017-01-22 16:04:01
【问题描述】:
我正在自学 Java 中的多线程。我的虚拟示例是我想要排序的大量记录(二维数组)列表。单线程方法是使用循环遍历记录列表和排序。我想多线程我的程序以使用固定数量的线程对我的列表进行排序,在这种情况下为 2。一个线程将对列表的前半部分进行排序,第二个线程将对剩余的一半进行排序。然后我想输出现在排序的记录列表的结果。
如何创建工作线程池并对记录列表进行排序?我需要担心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() -
您忘记了需要执行的第三步 - 合并排序后的结果。研究归并排序算法!
标签: java multithreading