假设我有 1000 个文件要读取,由于某些限制,我想并行读取最多 5 个文件。而且,一旦其中一个完成,我想要一个新的开始。
我有一个包含文件列表的主函数,每当一个线程完成时,我都会尝试更改计数器。但它不起作用!
有什么建议吗?
下面是主函数循环
for (final File filename : folder.listFiles()) {
Object lock1 = new Object();
new myThread(filename, lock1).start();
counter++;
while (counter > 5);
}
最佳答案
像这样产生线程不是要走的路。使用 ExecutorService
并将池指定为 5。将所有文件放入 BlockingQueue
或其他线程安全集合中,所有正在执行的文件都可以 poll()
随意。
public class ThreadReader {
public static void main(String[] args) {
File f = null;//folder
final BlockingQueue<File> queue = new ArrayBlockingQueue<File>(1000);
for(File kid : f.listFiles()){
queue.add(kid);
}
ExecutorService pool = Executors.newFixedThreadPool(5);
for(int i = 1; i <= 5; i++){
Runnable r = new Runnable(){
public void run() {
File workFile = null;
while((workFile = queue.poll()) != null){
//work on the file.
}
}
};
pool.execute(r);
}
}
}
关于java - 如何在 Java 中设置线程限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8651427/