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);     } } 请教一下这样可以吗?因为没有原题也没法测了
点赞 评论

相关推荐

喜欢飞来飞去的雪碧在刷代码:可以试一试字节
点赞 评论 收藏
分享
豆泥🍀:同26届,加油,我也还没找到查看图片
点赞 评论 收藏
分享

牛客热帖

更多
牛客网
牛客企业服务