如何在Java中进行线程限制 [英] How to make a thread limit in Java
问题描述
假设我要读取1000个文件,由于某些限制,我想最多并行读取5个文件.而且,一旦其中一个完成,我希望一个新的开始.
Let's say I have 1000 files to read and because of some limits, I want to read maximum 5 files in parallel. And, as soon as one of them is finished, I want a new one starts.
我有一个具有文件列表的主要功能,每当一个线程完成时,我尝试更改一个计数器.但这不起作用!
I have a main function who have the list of the files and I try changing a counter whenever one thread is finished. but it doesn't works!
有什么建议吗?
以下是主要功能循环
for (final File filename : folder.listFiles()) {
Object lock1 = new Object();
new myThread(filename, lock1).start();
counter++;
while (counter > 5);
}
推荐答案
这样的散布线程是不可行的.使用ExecutorService
并将池指定为5.将所有文件放入BlockingQueue
或另一个线程安全的集合中,所有正在执行的文件都可以随意poll()
.
Spawning threads like this is not the way to go. Use an ExecutorService
and specify the pool to be 5. Put all the files in something like a BlockingQueue
or another thread-safe collection and all the executing ones can just poll()
it at will.
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中进行线程限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!