面试题:多线程按顺序输出

今天看了一个帖子,https://blog.csdn.net/jiaobuchong/article/details/86555208
想回复他,但代码没贴成功,就另开个帖子。

愿问题:编写一个程序,开启 3 个线程,这三个线程的 名字 分别为 A、B、C,每个线程将自己的 名字 在屏幕上打印 10 遍,要求输出的结果必须按顺序显示。如:ABCABCABC……

我直接贴代码吧。

package cn.tx.thread.printsequencely;

public class PrintSequencely implements Runnable {

    static Object oLock = new Object();
    static int nSequence = 0;
    int nMySequence = 0;

    public PrintSequencely(int nMySequence) {
        this.nMySequence = nMySequence;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            synchronized (oLock) {
                while (nSequence % 3 != nMySequence) {
                    try {
                        oLock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.print(Thread.currentThread().getName());
                nSequence++;
                oLock.notifyAll();
            }
        }
    }


    public static void main(String[] args) {
        PrintSequencely A = new PrintSequencely(0);
        PrintSequencely B = new PrintSequencely(1);
        PrintSequencely C = new PrintSequencely(2);

        Thread ta = new Thread(A);
        Thread tb = new Thread(B);
        Thread tc = new Thread(C);

        ta.setName("A");
        tb.setName("B");
        tc.setName("C");

        ta.start();
        tb.start();
        tc.start();

    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值