0

こんにちは、「threadedSort」でスレッドを実行しようとしていますが、void を返すため、従来の void run メソッドを使用できません。私も同期メソッドを使用してみましたが、違いはないと思います...リエントラントメソッドと同じで、何が間違っているのかわかりません。

 private static String[] getDatathread(File file) throws IOException {

        ArrayList<String> data = new ArrayList<String>();
        BufferedReader in = new BufferedReader(new FileReader(file));
        // Read the data from the file until the end of file is reached
        while (true) {

            String line = in.readLine();
                if (line == null) {
                    // the end of file was reached

                    break;
                } else {
                    //synchronized(line){
                    lock.lock();
                    try{
                     data.add(line);   
                    }finally{
                      lock.unlock();
                    }

                    //}
                }

        }

        //Close the input stream and return the data
        in.close();
        return data.toArray(new String[0]);

    }
}


public static String[] threadedSort(File[] files) throws IOException, InterruptedException {
        String[] sortedData = new String[0];

        for (File file : files) {
            String[] data = getDatathread(file);
            Thread.sleep(100);
            data = MergeSort.mergeSort(data);
            sortedData = MergeSort.merge(sortedData, data);
        }

        return sortedData;
    }
4

1 に答える 1

0

コードで同期ブロックまたは再入可能ロックを使用した理由がわかりません。ブロックで使用されるリソースがまったく共有されていないブロックでロックを使用したようです。
メソッド threadedSort を並行して実行し、結果のデータ オブジェクトを取得する場合は、返されるデータをクラス変数として指定し、後でオブジェクトをフェッチするだけです。

于 2016-01-16T15:52:57.130 に答える