使用多线程处理子目录中的文件

时间:2019-01-07 12:41:47

标签: java multithreading

我们在多个文件中有多个管理目录,我想以以下方式使用多线程处理文件。 1)每个管理目录只有一个线程。 2)每个管理员分配的线程将按顺序处理子目录中的文件。

1 个答案:

答案 0 :(得分:0)

Well, I'm not going to do your homework for you, but I'll get you started.

What you want is to do is to use an ExecutorService, which will manage the threads for you.

First create a class that implements Runnable, with a member variable of a java.io.File, which will point to the subdirectory you are going to process Inside the class's run method, do whatever is you want to do for each subdirectory.

Then create your main class, which will first create an ExecutorService, then interrogate your top level directory to find the subdirectories. For each subdirectory, create a new instance of your class above and ask the ExecutorService to execute it.

Here's a good example: https://examples.javacodegeeks.com/core-java/util/concurrent/executorservice/java-executorservice-example-tutorial/