public class LoaderBean {
protected void download(List<File> files, String path, String nThreads) {
for (File file : files) {
new Downloader(file.getUrl(), path, file.getName()).startDownload();
System.out.println(Thread.currentThread().getName());
System.out.println(" ============================== ");
}
}
}
Есть такой код загрузки файлов. На входи приходит файл со списком файлов, путь, куда сохранять и количество потоков, для загрузки этих файлов. Я не совсем понимаю, как должна происходить загрузка через потоки.
protected void download(List<File> files, String path, String nThreads) {
for (File file : files) {
ExecutorService pool = Executors.newFixedThreadPool(Integer.parseInt(nThreads));
pool.submit(new Runnable() {
@Override
public void run() {
new Downloader(file.getUrl(), path, file.getName()).startDownload();
System.out.println(Thread.currentThread().getName());
System.out.println(" ============================== ");
}
});
}
}
Я пробовал такой код, но работал только один поток.
Вот этот код начал работать, однако, если убрать join, то перестаёт скачивать. В чём проблема может быть?
public class LoaderBean {
protected void download(List<File> files, String path, String nThreads) throws InterruptedException {
int countTreads = 0;
int n = Integer.parseInt(nThreads);
while(countTreads < files.size()) {
Thread[] threads = new Thread[Integer.parseInt(nThreads)];
for (int j = 0; j < n && j + countTreads != files.size(); ++j) {
threads[j] = new Thread(new MyThread(files.get(countTreads + j), path),
String.format("Thread %d", j));
}
if(countTreads + threads.length < files.size()) {
countTreads = countTreads + threads.length;
}
startThreads(threads);
}
}
private static void startThreads(Thread[] threads) throws InterruptedException {
for (Thread thread : threads) {
if(thread == null){
System.exit(0);
}
thread.start();
//thread.join();
}
}
}
class MyThread implements Runnable {
private String path;
private File file;
MyThread(File file, String path){
this.path = path;
this.file = file;
}
public void run() {
new Downloader(file.getUrl(), path, file.getName()).startDownload();
System.out.println(Thread.currentThread().getName());
System.out.println(" ============================== ");
}
}
Апостиль в Лос-Анджелесе без лишних нервов и бумажной волокиты
Основные этапы разработки сайта для стоматологической клиники
Продвижение своими сайтами как стратегия роста и независимости