关注
import java.util.Scanner;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
//消费者
class Task implements Runnable {
private final CountDownLatch startGate;
private final CountDownLatch endGate;
private final BlockingQueue<String> queue;
private final AtomicInteger count;
Task(CountDownLatch startGate, CountDownLatch endGate, BlockingQueue<String> queue, AtomicInteger count) {
this.startGate = startGate;
this.endGate = endGate;
this.queue = queue;
this.count = count;
}
@Override
public void run() {
try {
startGate.await();
while (!queue.isEmpty()) {
try {
if (queue.take().contains("u51")) {
count.incrementAndGet();
}
} finally {
endGate.countDown();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
final BlockingQueue<String> queue = new LinkedBlockingQueue<>();
final AtomicInteger count = new AtomicInteger();
Scanner scanner = new Scanner(System.in);
//闭锁
final CountDownLatch startGate = new CountDownLatch(1);
final CountDownLatch endGate = new CountDownLatch(3);
while (scanner.hasNextLine()) {
queue.put(scanner.nextLine());
}
Task task = new Task(startGate, endGate, queue, count);
new Thread(task).start();
new Thread(task).start();
new Thread(task).start();
startGate.countDown();
endGate.await();
System.out.println(count);
}
}
请教一下这样可以吗?因为没有原题也没法测了
查看原帖
点赞 评论
相关推荐

点赞 评论 收藏
分享
点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 我的实习收获 #
27033次浏览 462人参与
# 非技术岗简历怎么写 #
209462次浏览 2857人参与
# 实习吐槽大会 #
28429次浏览 136人参与
# 26届秋招投递记录 #
2701次浏览 88人参与
# 晒一晒你的工位 #
84924次浏览 302人参与
# 2025牛客秋招季 #
2704次浏览 90人参与
# 如果有时光机,你最想去到哪个年纪? #
46891次浏览 796人参与
# 双非能在秋招上岸吗? #
214901次浏览 1137人参与
# 我的租房踩坑经历 #
23617次浏览 254人参与
# 打工人的工作餐日常 #
40359次浏览 343人参与
# 穿越回高考你还会选现在的专业吗 #
19763次浏览 251人参与
# 软开人,说说你的烦心事 #
48002次浏览 359人参与
# 被AI治愈的瞬间 #
52191次浏览 597人参与
# 毕业旅行去哪玩儿 #
1123次浏览 32人参与
# 怎么防止在试用期被辞退 #
122236次浏览 910人参与
# 关于提前批我想问 #
201760次浏览 2143人参与
# 高学历就一定能找到好工作吗? #
47570次浏览 591人参与
# 携程求职进展汇总 #
531207次浏览 3962人参与
# 打工人锐评公司红黑榜 #
145597次浏览 912人参与
# 夸夸我的求职搭子 #
190932次浏览 1891人参与