如何在Java中同时运行线程和访问相同资源

时间:2018-12-07 12:22:36

标签: java multithreading file filereader

下面,我写了一个可运行的文件来运行目录并解析其中的csv文件。运行当前代码,以便T1和T2都读取目录中的所有文件。如何做到这一点,以使T1和T2能够同时运行,但不能访问相同的文件进行解析。

public class ThreadDemo{
    public static void main(String[] args){
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        executorService.execute(new Task());//T1
        executorService.execute(new Task());//T2
        executorService.shutdown();
    }
}

class Task implements Runnable {
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            String line = "";
            String dirName = "/dir/location";
            File[] fileList = new File(dirName).listFiles();
            BufferedReader br = null;
            for (File file :  fileList){
                br = new BufferedReader(new FileReader(file.getName()));
                while ((line = br.readLine()) != null){
                    //parse few vaule
                }
                System.out.println("The file name is this :::: "+file.getName());
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我首先将File的数组分成2个子数组,然后为每个任务分配一个子数组。像这样:

public class ThreadDemo {
    public static void main(String[] args) {
        String dirName = "/dir/location";
        File[] fileList = new File(dirName).listFiles();
        int mid = fileList.length / 2;
        File[] fileListOne = Arrays.copyOfRange(fileList, 0, mid);
        File[] fileListTwo = Arrays.copyOfRange(fileList, mid, fileList.length);
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        executorService.execute(new Task(fileListOne));//T1
        executorService.execute(new Task(fileListTwo));//T2
        executorService.shutdown();
    }
}

class Task implements Runnable {
    private final File[] fileList;

    public Task(File[] fileList) {
        this.fileList = fileList;
    }

    @Override
    public void run() {
        try {
            String line = "";
            for (File file : fileList) {
                try (BufferedReader br = new BufferedReader(new FileReader(file.getName()))) {
                    while ((line = br.readLine()) != null) {
                        //parse few vaule
                    }
                    System.out.println("The file name is this :::: " + file.getName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}