java download multiple files using threads

后端 未结 5 1914
庸人自扰
庸人自扰 2020-11-30 02:54

I am trying to download multiple files that matches a pattern using threads. The pattern could match 1 or 5 or 10 files of diff sizes.

lets say for simplicity sake

5条回答
  •  天涯浪人
    2020-11-30 03:09

    Yes, you certainly could create a new thread inside the for-loop. Something like this:

    List threads = new ArrayList();
    for (String name : fileNames) {
      Thread t = new Thread() {
        @Override public void run() { downloadFile(name, toPath); }
      };
      t.start();
      threads.add(t);
    }
    for (Thread t : threads) {
      t.join();
    }
    // Now all files are downloaded.
    

    You should also consider using an Executor, for example, in a thread pool created by Executors.newFixedThreadPool(int).

提交回复
热议问题