0
我编写了一个排序程序,为每个sort
方法调用创建一个单独的线程,所有线程都写入共享变量以说明它们的排序类型(字符串,整数等)完成。我使用CountDownLatch
等待所有线程完成并检索该共享变量以找出失败者。我已经运行我的代码,似乎得到了正确的结果,但是我在Java线程方面的经验不足,使我不确定以下程序的有效性。这可能是一个普遍的问题:下面的程序有什么错误吗?使用Java查找输出线程CountDownLatch
public class LatchedSorter {
private SortingType loserType;
private final CountDownLatch stopLatch;
public LatchedSorter(CountDownLatch stopLatch) {
this.stopLatch = stopLatch;
}
public synchronized SortingType getLoserType() {
return this.loserType;
}
public synchronized void setLoserType(SortingType loserType) {
this.loserType = loserType;
}
public <T extends Comparable<? super T>> void sort(final List<T> list, final SortingType type) {
Runnable current = new Runnable() {
public void run() {
Collections.sort(list);
setLoserType(type);
stopLatch.countDown();
}
};
new Thread(current).start();
}
}
和主呼叫者是这样的:
public static void main(String args[]){
CountDownLatch cdl = new CountDownLatch(2);
LatchedSorter cs = new LatchedSorter(cdl);
List<String> stringList = new ArrayList<String>();
List<Integer> integerList = new ArrayList<Integer>();
for(int i=0; i<1000; i++) {
stringList.add(String.valueOf(i));
integerList.add(i);
}
cs.sort(integerList, SortingType.Integers);
cs.sort(stringList, SortingType.Strings);
try {
cdl.await();
System.out.println("Loser thread is: "+cs.getLoserType());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
这很好,但是我不确定你是否真的需要'SortingType'字段的'synchronized'访问器(或者甚至使它成为volatile),因为文档说在一个线程中, countDown()'*在'await()'成功返回后,在另一个线程中发生行动,这就是你正在做的事情。 –
@BrunoReis谢谢你的回答,我只是看了一眼,我认为你是对的,因为赋值运算符是原子的,所以我甚至不需要使setter同步。你对此有何想法? – Abidi