0

嗨,我尝试在我的“threadedSort”上运行一个线程,但我不能使用传统的 void 运行方法,因为它返回 void。我也尝试使用同步方法,但我认为它没有任何区别......与可重入方法相同,我不知道我做错了什么。

 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 回答