简体   繁体   中英

Finding a loser thread using Java CountDownLatch

I wrote a sorting program that creates a separate thread for each sort method call, all of the threads write to a shared variable to say what type (String, Integers and etc) of sorting they have done. I use CountDownLatch to wait for all of the threads to finish and retrieve that shared variable to find out the loser. I have run my code and seems to be getting the right result but my lack of experience in Java Threads makes me uncertain about the validity of the following program. It might be a bit general question: is there something terribly wrong with the following program?

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();
    }

}

And the Main caller is like this:

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();
        }
    }

There is nothing wrong with the program and should never show any data or race conditions. Its perfectly fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM