Java:依赖于文件的线程

时间:2017-01-31 14:29:00

标签: java multithreading

我想知道以下代码出了什么问题,如果有人可以帮助我的话。我要做的是:

  • 创建一个包含一些.txt文件的文件夹
  • 为该文件夹中包含的每个.txt文件创建一个帖子
  • 为每个线程执行任务(在此特定情况下只需等待几秒钟)
  • 然后在完成任务后,删除单个线程所依赖的文件。

我的问题是,每次运行代码时,一切都运行正常,在执行任务后删除所有文件。结果是只删除了一个.txt文件,其他文件仍在该文件夹中。 :/

我做错了什么?

任何帮助都会非常棒。提前谢谢。

朱利安:D

public abstract class Threads {
static Formatter x;
public static void main(String[] args) throws IOException {


    //create folder with 10 .txt-files
    File theFolder = new File("C:\\Users\\Gamer\\Desktop\\TheFolder\\");
    theFolder.mkdir();

    for(int files = 0; files <= 10; files++) {
        x = new Formatter("C:\\Users\\Gamer\\Desktop\\TheFolder\\"+files+".txt");
    } 

    System.out.println("Created the folder and files");
    //Close the formatter
    x.close();


    //Start a thread for each file in that folder
    System.out.println(Files.list(Paths.get("C:\\Users\\Gamer\\Desktop\\TheFolder\\")).count());
    Thread[] threads = new Thread[(int) Files.list(Paths.get("C:\\Users\\Gamer\\Desktop\\TheFolder\\")).count()];

    for(int i = 0; i < threads.length; i++) {
        int del = i;
        threads[i] = new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(2000);

                    //after timeout of ones thread, terminate file
                    File theFile = new File("C:\\Users\\Gamer\\Desktop\\TheFolder\\"+del+".txt");
                    theFile.delete(); 
                    System.out.println("deleted file: "+del);
                } catch (InterruptedException e) {e.printStackTrace();}
            }
        });
        threads[i].start(); System.out.println("Started thread no. "+i);}       

    System.out.println("end");
    }
}

1 个答案:

答案 0 :(得分:6)

您只关闭一个格式化程序(最后一个),因此所有其他文件仍然具有打开的句柄,并且无法删除。试试这个:

 for(int files = 0; files <= 10; files++) {
     x = new Formatter("C:\\Users\\Gamer\\Desktop\\TheFolder\\"+files+".txt");
     x.close();
 } 
 //x.close(); <-- this will only close the last formatter that is assigned to "x" after the loop is done