-
Thread
Hi Guys
Nowdays I am developing programe to search particulr file in the folder.In here what i am doing is getting files list in the given foder and save it in to string array.Ater that search process start from the first element of the string array and in the same time another search process start form the final elemnt to first element ,it'e mean backward searching.I think doing like above procedure it's will take less time compare to noraml searching.
so,what i want to do is using thread.Please I kindly accept any suggestion for do this.
Thank you
-
Code:
import java.io.*;
import java.util.*;
public class SearchTest {
static Random seed = new Random();
static String[] fileNames;
static String target;
static long start;
public static void main(String[] args) {
String searchDir = ".";
File folder = new File(searchDir);
List<String> list = new ArrayList<String>();
collectFileNames(folder, list);
fileNames = list.toArray(new String[list.size()]);
int index = seed.nextInt(fileNames.length);
target = fileNames[index];
System.out.printf("target = %s at index = %d of %d files%n",
target, index, fileNames.length);
start = System.currentTimeMillis();
new Thread(forward).start();
new Thread(reverse).start();
}
private static void collectFileNames(File folder, List<String> list) {
folder.setReadOnly();
File[] files = folder.listFiles();
for(int j = 0; j < files.length; j++) {
list.add(files[j].getName());
if(files[j].isDirectory())
collectFileNames(files[j], list);
}
}
private static synchronized void post(int index, long end, String caller) {
long time = end - start;
System.out.printf("%s found %s at index %d in %d millis%n",
caller, target, index, time);
}
private static Runnable forward = new Runnable() {
public void run() {
for(int j = 0; j < fileNames.length; j++) {
if(fileNames[j].equals(target)) {
long end = System.currentTimeMillis();
post(j, end, "forward");
break;
}
}
}
};
private static Runnable reverse = new Runnable() {
public void run() {
for(int j = fileNames.length-1; j >= 0; j--) {
if(fileNames[j].equals(target)) {
long end = System.currentTimeMillis();
post(j, end, "reverse");
break;
}
}
}
};
}