java多线程 两个线程交叉打印1到100的数字

目录

解法1 静态原子变量 死循环

解法2 静态变量 死循环/wait 锁住class

解法3 静态变量 ReentrantLock Condition

扩展问题


注意:本文参考  面试题精选:两个线程按顺序交替输出1-100 - xindoo - 博客园

具体题目是这样的,两个线程交替按顺序输出1-100,第一个线程只能输出偶数,第二线程输出奇数,想象下两个小孩轮流喊数。

两个线程交替输出,这就意味着它俩是需要协同的,协同意味着二者之间要有信息传递,如何相互传递信息? 你可能直接想到,既然是0-100的数按顺序交替输出,那么每个进程只需要时不时看看计数器的值,然后看是否轮到自己输出了就行。没错,这就是解法一的思路。

解法1 静态原子变量 死循环

有了上面的思路,你肯定能快速写出以下代码:

public class PrintNumber extends Thread {
    private static int cnt = 0;
    private int id;  // 线程编号 
    public PrintNumber(int id) {
        this.id = id;
    }

    @Override
    public void run() {
        while (cnt < 100) {
            while (cnt%2 == id) {
                cnt++;
                System.out.println("thread_" + id + " num:" + cnt);
            }
        }
    }

    public static void main(String[] args) {
        Thread thread0 = new PrintNumber(0);
        Thread thread1 = new PrintNumber(1);
        thread0.start();
        thread1.start();
    }
}

但当你实际运行后会发现!!!

thread_0 num:1
thread_0 num:3
thread_1 num:3
thread_1 num:5
thread_1 num:6
thread_0 num:5
thread_0 num:8
thread_0 num:9
thread_1 num:8
thread_0 num:11
thread_1 num:11
.........

不仅顺序不对,还有重复和丢失!问题在哪?回到代码中cnt++; System.out.println("thread_" + id + " num:" + cnt); 这两行,它主要包含两个动作,cnt++和输出,当cnt++

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值