【问题标题】:How do I stop threads from taking another threads job?如何阻止线程占用另一个线程工作?
【发布时间】:2017-09-09 14:42:12
【问题描述】:

我取了一个给定的 int 数组并将其分解为多个子数组并放入一个 ArrayList。

1) 我需要为 a 的每个索引生成一个线程。 (这不起作用并导致线程使用相同的数据)

2)我需要通过快速排序类发送每个线程进行排序。(就目前而言,这是可行的)

3)我还需要将所有线程排序数组合并到一个排序数组中。(也不知道如何做到这一点)

public void run(ArrayList<int[]> a) {
        Quicksort x = new Quicksort();
        for (int i = 0; i < a.size(); i++) {
            store = a.get(i);
            System.out.println(store);
            new Thread() {
                public void run() {
                    x.sort(store);
                    System.out.println(Arrays.toString(store));

                }
            }.start();

        }
    }
public class Quicksort {
     private int array[];
    private int length;

    public void sort(int[] inputArr) {

        if (inputArr == null || inputArr.length == 0) {
            return;
        }
        this.array = inputArr;
        length = inputArr.length;
        quickSort(0, length - 1);
    }

    private void quickSort(int lowerIndex, int higherIndex) {

        int i = lowerIndex;
        int j = higherIndex;

        int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2];

        while (i <= j) {

            while (array[i] < pivot) {
                i++;
            }
            while (array[j] > pivot) {
                j--;
            }
            if (i <= j) {
                exchangeNumbers(i, j);
                i++;
                j--;
            }
        }
        if (lowerIndex < j)
            quickSort(lowerIndex, j);
        if (i < higherIndex)
            quickSort(i, higherIndex);
    }

    private void exchangeNumbers(int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

}

我如何填充一个

public class ArrayLists {

    private ArrayList<int[]> List = new ArrayList<>();
public ArrayLists(int[] a, int size) {
    int[] temp = new int[size];
    int count = 0;
    while (count + size <= a.length) {
        temp = Arrays.copyOfRange(a, count, count + size);
        List.add(temp);
        count = count + size;
    }
    int[] temp2 = new int[a.length - count];
    if (count != a.length && count < a.length) {
        temp2 = Arrays.copyOfRange(a, count, a.length);
        List.add(temp2);
    }
    run(List);
}

【问题讨论】:

  • 那么问题是什么?
  • 如何阻止它在两个不同的线程中使用相同的数据
  • 问题可能不在于线程。你如何创建数组?发布一个 MVCE
  • 不确定 MVCE 是什么,但我展示了我如何填充 a。
  • 没有List的声明。然后你重复使用相同的数组(临时),同时只分配一个新的内存。这大概是个错误。如果这可行,请告诉我,我会将其发布为答案

标签: java arrays multithreading sorting merge


【解决方案1】:

问题是我如何使用 store 变量。我需要一个最终的 int[] 而不是一个静态的 int[] 全局变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多