java download multiple files using threads

后端 未结 5 1906
庸人自扰
庸人自扰 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:16

    All the Above mentioned approach creates Threads but the actual Concurreny is not achieved.

    ExecutorService pool = Executors.newFixedThreadPool(5);
    final File folder = new File("YOUR_FILES_PATH");
    int l = folder.listFiles().length;
    System.out.println("Total Files----"+folder.listFiles().length);
    long timeStartFuture = Calendar.getInstance().getTimeInMillis();
        pool.execute(new DownloadFile(folder,0,l/2));
        pool.execute(new DownloadFile(folder,(l/2),l));
        pool.shutdown();
        try {
            pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
        long timeEndFuture = Calendar.getInstance().getTimeInMillis();
        long timeNeededFuture = timeEndFuture - timeStartFuture;
        System.out.println("Parallel calculated in " + timeNeededFuture + " ms");
    

    The above program is used to achieve concurreny and please modify as per your requirement.

提交回复
热议问题