我正在构建一个项目,我想在其中并行生成多个链表,然后合并它们,最后想要使用多线程对它进行排序。我已经并行创建了链接列表。实际上我不确定它是顺序生成还是并行生成。任何人都可以帮助我解决问题。
我的代码是:
public class ParallelMaximizer {
int numThreads;
Random r = new Random();
int Low = 10;
int High = 100;
int numElements = 10;
static ParallelMaximizerWorker[] workers;
public ParallelMaximizer(int numThreads) {
workers = new ParallelMaximizerWorker[numThreads];
}
public static void main(String[] args) {
int numThreads = 4;
ParallelMaximizer maximizer = new ParallelMaximizer(numThreads);
LinkedList<Integer> list = new LinkedList<Integer>();
try {
System.out.println("Maximum Number -> " + maximizer.max(list));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public int max(LinkedList<Integer> list) throws InterruptedException {
int max = Integer.MIN_VALUE;
for (int j=0; j<workers.length; j++){
for (int i=0; i<numElements; i++){
int numValues = r.nextInt(High-Low) + Low;
list.add(numValues);
}
System.out.println("LinkedList -> " + list);
for (int i=0; i < workers.length; i++) {
workers[i] = new ParallelMaximizerWorker(list);
workers[i].start();
}
for (int i=0; i<workers.length; i++){
try {
workers[i].join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
list = new LinkedList<>();
}
for(ParallelMaximizerWorker pmw : workers){
max = Math.max(max, pmw.partialMax);
}
return max;
}
}
其他课程是:
public class ParallelMaximizerWorker extends Thread {
protected LinkedList<Integer> list;
protected int partialMax = Integer.MIN_VALUE; // initialize to lowest value
public ParallelMaximizerWorker(LinkedList<Integer> list) {
this.list = list;
}
public void run() {
while (true) {
int number;
synchronized(list) {
if (list.isEmpty())
return; // list is empty
number = list.remove();
}
partialMax = Math.max(number, partialMax);
}
}
public int getPartialMax() {
return partialMax;
}
}