我有一个类可以对通用列表进行一些递归合并排序,只要该元素实现 Comparable。我正在尝试使代码成为多线程以提高性能,为此,我有一个静态变量maxThreads
来保持我创建的线程数不会爆炸,并且我有一个静态变量currentThreads
来跟踪数量我目前正在运行的线程。我的变量似乎存在竞争条件currentThreads
,但我无法提出解决方案来解决它。
import java.util.ArrayList;
import java.util.List;
public class ThreadedMergeSorter<E extends Comparable<? super E>> implements, Runnable
{
private List<E> list;
private List<E> left, right;
private Thread t1, t2;
private static final int maxThreads = 4;
private static AtomicInteger currentThreads = new AtomicInteger(0);
private ThreadedMergeSorter(List<E> list)
{
this.list = list;
}
public ThreadedMergeSorter(){}
/**
* Sorts a List<E> using the merge sorting algorithm
* @param list the list to be merge sorted
* @return
* @throws InterruptedException
*/
public void sort(List<E> list)
{
if(list.size() > 1)
{
left = new ArrayList<E>(list.subList(0, list.size()/2));
right = new ArrayList<E>(list.subList(list.size()/2, list.size()));
list.clear();
if(currentThreads.get() < maxThreads)
{
t1 = new Thread(new ThreadedMergeSorter<E>(left));
t1.start();
currentThreads.incrementAndGet();
}
else sort(left);
if(currentThreads.get() < maxThreads)
{
t2 = new Thread(new ThreadedMergeSorter<E>(right));
t2.start();
currentThreads.incrementAndGet();
}
else sort(right);
try{
if(t1 != null)
{
t1.join();
currentThreads.decrementAndGet();
}
if(t2 != null)
{
t2.join();
currentThreads.decrementAndGet();
}
}catch(InterruptedException e){}
list.addAll(mergeSortedLists(left, right));
}
}
/**
* Merges two previously sorted List<E extends Comparable<E>> into a single List
* @param leftArray a List of previously sorted elements
* @param rightArray a List of previously sorted elements
* @return an new sorted List
*/
private List<E> mergeSortedLists(List<E> leftList, List<E> rightList)
{
ArrayList<E> list = new ArrayList<E>();
while(!leftList.isEmpty() && !rightList.isEmpty())
{
if((leftList.get(0)).compareTo(rightList.get(0)) <= 0)
list.add(leftList.remove(0));
else
list.add(rightList.remove(0));
}
if(!leftList.isEmpty())
list.addAll(leftList);
if(!rightList.isEmpty())
list.addAll(rightList);
return list;
}
@Override
public void run()
{
sort(this.list);
}
}
问题在于语句和块的sort(List<E> list)
方法。if
try catch