Multithreading inside for loop
I am trying to read the multiple files from a directory and create a
separate thread for every file.While iterating the loop, the anonymous
inner class cannot use non final variables.
My question is how to create multiple threads inside a loop.(I am required
to manually create threads for each file, cant use executor service or
something else)
class de
{
void commit(File x)
{
int sum =0;
try{
FileInputStream fin = new FileInputStream(x);
byte[]b= new byte[5000];
fin.read(b);
for (byte digit:b)
{
sum=digit+sum;
}
System.out.println(sum);
}
catch(Exception e)
{
}}
public static void main (String args[])
{
File f = new File("C:\\Users\\Ankur\\workspace\\IO\\Numbers");
File []store = f.listFiles( new FilenameFilter()
{
public boolean accept(File f, String name)
{
return name.endsWith("txt");
}
}
);
for (File x: store)
{
Thread t = new Thread()
{
public void run ()
{
// new de().commit(x);
}
};
}
}
}
No comments:
Post a Comment