题解 | #多线程打印#

多线程打印

https://www.nowcoder.com/practice/835d678e89a848508389c462e5173252

import java.util.concurrent.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {

        final Semaphore numS = new Semaphore(1);
        final Semaphore letterS = new Semaphore(0);

        Thread numThread = new Thread() {
            int i = 1;

            @Override
            public void run() {
                while (i <= 52) {
                    try {
                        numS.acquire();
                        System.out.print(i);
                        i++;
                        System.out.print(i);
                        i++;
                        letterS.release();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                }
            }
        };

        Thread letterThread = new Thread() {

            char letter = 'A';

            @Override
            public void run() {
                while (letter <= 'Z') {
                    try {
                        letterS.acquire();
                        System.out.print(letter);
                        letter += 1;
                        System.out.print(" ");
                        numS.release();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        };

        numThread.start();
        letterThread.start();
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
03-15 10:59
已编辑
爱写代码的菜code...:哎,自己当时拿到字节offer的时候也在感叹终于拿到了,自己当时最想去的企业就是字节,结果还是阴差阳错去了鹅厂。祝uu一切顺利!!!
点赞 评论 收藏
分享
牛马人的牛马人生:太舒服了接接接
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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