我正在尝试创建Merge Sort的多线程版本,我正在使用执行程序(请告诉我,如果还有其他更好的方法)。我希望两个线程同时运行。我是Executors的新手,即使在看了一些教程后也发现很难编码。当然,除了执行者之外的任何并行化方法都是最受欢迎的。
public static void ASC(int[] input_array, int left, int right, int[] temp_array) // Sorts in ascending order
{
if(left < right)
{
int middle = ( left + right )>>>1 ; // Same as (left + right)/2, but avoids overflow for large left and right and is probably faster
// I want to run these 2 codes in 2 threads simultaneously
ASC(input_array, left, middle, temp_array);
ASC(input_array, middle+1, right, temp_array);
// And I want the execution to stop here until the threads are finished
// I know invokeAll() will do the job but I cant seem to code it properly
// Pls tell me how to do it properly along with what classes to import as Im new to Executors.
// Any other method of parallelizing is most welcomed
// The part below is the Merge Procedure
int j = middle + 1;
int temp_indx = left;
int left2 = left;
while((left <= middle) && (j <= right))
{
if (input_array[left] < input_array[j])
{
temp_array[temp_indx] = input_array[left];
left = left + 1;
}
else
{
temp_array[temp_indx] = input_array[j];
j = j + 1;
}
temp_indx = temp_indx + 1;
}
while(left <= middle)
{
temp_array[temp_indx] = input_array[left];
left = left + 1;
temp_indx = temp_indx + 1;
}
while(j <= right)
{
temp_array[temp_indx] = input_array[j];
j = j + 1;
temp_indx = temp_indx + 1;
}
while(right >= left2)
{
input_array[right] = temp_array[right];
right = right - 1;
}
}
}