0
I am looking for files using threads, the code I developed looks for the right file , but it turns out that it does not finish the execution when it finds , or if it does not find it continues running.
import java.io.File;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import javax.swing.JOptionPane;
public class ProcuraArquivoThreadPool implements Runnable{
private static boolean achou;
private File pasta;
private String arquivo;
private Executor pool;
public ProcuraArquivoThreadPool(File pasta, String arquivo, Executor pool) {
this.pasta = pasta;
this.arquivo = arquivo;
this.pool = pool;
}
public static void procura(String pasta, String arquivo, Executor pool) {
achou = false;
pool.execute(new ProcuraArquivoThreadPool(new File(pasta), arquivo, pool));
}
public void run() {
if(achou){
return;
}
for(File f : pasta.listFiles()){
if(achou){
break;
} else if(f.isDirectory()){
pool.execute(new ProcuraArquivoThreadPool (f, arquivo, pool));
} else if(f.getName().equalsIgnoreCase(arquivo)){
System.out.println("Achei: " + f.getPath());
achou = true;
break;
}
}
}
public static void main (String[] args){
Scanner teclado = new Scanner(System.in);
//System.out.println("Digite o caminho da Pasta");
//String pasta = teclado.nextLine();
System.out.println("Digite o arquivo a ser procurado");
String arquivo = teclado.nextLine();
String pasta = "C:/";
System.out.println("Procurando......");
ScheduledExecutorService threadpool = Executors.newScheduledThreadPool(4);
procura(pasta, arquivo,threadpool);
}
}
Aren’t we missing shutdown in the thread pool? Try adding
thread pool.shutdown();
after the call toprocura(pasta, arquivo, threadpool);
– Piovezan
he doesn’t even execute the search method if I put after the call
– Lucas Luan
True, because there are more calls to
execute()
. Maybe it works if you put the shutdown after thefor
. But the ideal is to restructure the code, only at the moment I won’t be able to see that.– Piovezan