简体   繁体   中英

Multi-thread MergeSort

I would like to realise a mergesort with multithreading.

so here is my code :

public class MergeSort<E extends Comparable<T>> implements Runnable {

public void run() {
    mergeSort(array);
}

public synchronized void mergeSort(List<E> array) {     
    int size = array.size();
    if (size > 1){
        int mid = size / 2;
        List<T> l  = array.subList(0,mid);
        List<T> r = array.subList(mid,vec.size());
        Thread t = new Thread(new MergeSort<E>(left));
        Thread t2 = new Thread(new MergeSort<E>(right));
        t.start();
        t2.start();
        merge(l, r, array);
    }
}

I would like my MergeSort to run, create 2 new threads, and then the method call the merge and finishes his job. I tried without thread, juste by calling Mergesort(left)... It worked, so my algorithm is correct, but when I try with threads, the List is not sorted.

So, how to synchronize the threads? I Know there will be too much threads, but I just want to know how to synchronize to sort the list.

我无法确切地说出原因,因为缺少某些代码,但看起来确实像是您两次用“ left”调用mergesort一样。

Couple of things to keep in mind:

  1. Just by creating thread, dont assume that thread would start running instanteneously.
  2. You are injecting left as parameter to both your thread instead of l and r.
  3. If at all you want it to work, you would need thread pair each one to do its task and once that is done, you could proceed with next two halves after merging the result.

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