题解 | #多线程#

多线程

http://www.nowcoder.com/practice/cd99fbc6154d4074b4da0e74224a1582

参考了前面的兄弟的答案,改了一丢丢

import java.util.Scanner;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int a = in.nextInt();
            System.out.println(solution2(a));
        }
    }

   private static String solution2(int a) {
        StringBuilder stringBuilder = new StringBuilder(1032);
        //用于阻塞主线程 等4个子线程执行完
        CountDownLatch latch = new CountDownLatch(4);
        //1.作为4条线程共同的锁对象 2.用于控制线程的等待和唤醒
        AtomicInteger count = new AtomicInteger(0);
        for (int i = 0; i < 4; i++) {
            int finalI = i;
            new Thread(() -> {
                for (int j = 0; j < a; j++) {
                    synchronized (count) {
                        while (count.get() % 4 != finalI) {
                            try {
                                count.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        stringBuilder.append((char) ('A' + finalI));
                        count.getAndIncrement();
                        count.notifyAll();
                    }
                }
                latch.countDown();
            }).start();
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务