gpt4 book ai didi

java - LinkedBlockingQueue 仅返回多个线程之一

转载 作者:行者123 更新时间:2023-11-30 03:07:44 30 4
gpt4 key购买 nike

我创建了一个类来计算同一目录中给定文件中的单词数。由于文件非常大,我决定使用多线程来实现多个文件的计数。

当按照下面指定的方式运行 DriverClass 时,它会卡在线程一。我究竟做错了什么?当我迭代queue.take()时,人们会期望解析器等待某些内容被检索并继续。卡在线程 1 使我怀疑将() 放入队列时出现错误。

提前谢谢!

驱动程序类:

public class WordCountTest {
public static void main(String[] args){
if (args.length<1){
System.out.println("Please specify, atleast, one file");
}
BlockingQueue<Integer> threadQueue = new LinkedBlockingQueue<>();
Runnable r;
Thread t;

for (int i = 0; i<args.length; i++){
r = new WordCount(args[i], threadQueue);
t = new Thread(r);
t.start();

int total = 0;
for (int k = 0; k<args.length; k++){
try {
total += threadQueue.take();
} catch (InterruptedException e){
}
}
System.out.println("Total wordcount: " + total);
}
}
}

WordCount类:

public class WordCount implements Runnable {
private int myId = 0;
private String _file;
private BlockingQueue<Integer> _queue;
private static int id = 0;

public WordCount(String file, BlockingQueue<Integer> queue){
_queue = queue;
_file = file;
myId = ++id;
}

@Override
public void run() {
System.out.println("Thread " + myId + " running");
try {
_queue.put(countWord(_file));
} catch (InterruptedException e){

}
}

public int countWord(String file){
int count = 0;
try {
Scanner in = new Scanner(new FileReader(file));
while (in.hasNext()){
count++;
in.next();
}
} catch (IOException e){
System.out.println("File," + file + ",not found");
}
return count;
}
}

最佳答案

问题在于您正在使用嵌套循环,而您应该使用两个单独的循环:一个用于启动 WordCounts,另一个用于收集结果,例如

public class WordCountTest {
public static void main(String[] args){
Queue<Integer> threadQueue = new ConcurrentLinkedQueue<>();
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

CountDownLatch latch = new CountDownLatch(args.length);

for (int i = 0; i<args.length; i++){
CompletableFuture.runAsync(new WordCount(args[i], threadQueue), executor)
.thenRunAsync(latch.countDown(), executor);
}

latch.await();

int sum = 0;
for(Integer i : threadQueue) {
sum += i;
}
}
}

或者无论您想如何实现它,重点是在所有 WordCounts 开始之前您不应该开始收集结果。

关于java - LinkedBlockingQueue 仅返回多个线程之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34322773/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com