0
私はディレクトリのすべてのファイルを処理する必要がありますので、これは2つのセットに分割することを考えています。ファイルをQueue(Producer)に入れ、2番目の部分ではスレッドはファイルをキューから読み込んで処理を開始します。スレッドを使用してファイルをナンバーに格納
私が直面している問題は、ただ1つのスレッドがファイルをキューに入れて、残りのすべてがキューを空にしているということです。あなたのスキャン機能で
リーダークラス
package com.src.deloitte.helper;
import java.io.File;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
public class MyReader
{
int[] threads;
private long counter = 0;
final Queue exploreList = new ConcurrentLinkedQueue();
public MyReader(int arrayLen) {
threads = new int[arrayLen];
}
public void count() {
counter++;
}
public void done(int id, int counter) {
threads[id] = counter;
}
public static void main(String[] args)
{
MyReader me = new MyReader(5);
me.scan("c:\\myDirectory");}
void scan(String fileName)
{
File file = new File(fileName);
exploreList.add(file);
for(int i =0;i<threads.length;i++)
{
FileExplorer explorer = new FileExplorer(i,this);
Thread t = new Thread(explorer);
t.start();
}
}
}
FileExplorer
public class FileExplorer implements Runnable {
public int counter = 0;
public MyReader owner;
private int id;
public FileExplorer(int id, MyReader owner) {
this.id = id;
this.owner = owner;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() +"Entering into the run method");
while (!owner.exploreList.isEmpty()) {
try{
File file = (File) owner.exploreList.remove();
if (file.exists()) {
if (!file.isDirectory()) {
doThemagic(file);
} else {
// add the files to the queue
File[] arr = file.listFiles();
if (arr != null) {
for (int i = 0; i < arr.length; i++) {
owner.exploreList.add(arr[i]);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
// silent kill :)
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
owner.done(id, counter);
System.out.println(Thread.currentThread().getName() +" " + "total of files : " + counter);
}
private void doThemagic(File file) {
System.out.println(file.toString());
counter++;
}
}