【问题标题】:Running Threads on a File Method在文件方法上运行线程
【发布时间】:2016-01-16 03:29:06
【问题描述】:

您好,我尝试在我的“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;
    }

【问题讨论】:

    标签: java multithreading synchronization reentrantlock


    【解决方案1】:

    我不确定您为什么在代码中为此使用同步块或可重入锁。您似乎在块上使用了锁,而块中使用的资源没有以任何方式共享。
    如果您想并行运行 threadedSort 方法并获取结果数据对象,您只需指定要作为类变量返回的数据并稍后获取该对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-09
      • 2021-01-04
      相关资源
      最近更新 更多