Java线程中while中的同步代码块需要再次判断循环条件

今天做一道leetcode的多线程算法卡了近三个小时
最后发现跟wait和notify也没关系
把问题模型最简单化为以下代码:
两个测试方法,就是并发轮流打印1-5的数字

class Test{
    private  int n=5;
    private  int count=1;
    private final Object lock=new Object();
    Test(int n){
        this.n=n;
    }

    public void print1() throws InterruptedException {
        while (count<=n){
            //中断处
            synchronized (lock){
                System.out.println(count);
                count++;
            }
        }
    }

    public void print2() throws InterruptedException {
        while (count<=n){
            //中断处
            synchronized (lock){
                System.out.println(count);
                count++;
            }
        }
    }
}

之后输出的永远都是1-6
想不通为啥已经做了判断count小于等于5 还会输出6呢
原因是这样的
假设某情况:
第一次print1运行到中断处时 count为1 然后由于没有进入同步代码块 运行print2的线程抢到了运行权 然后一口气运行到了5 然后count++为6 运行完毕
然后回到了线程1的中断处 这时count已经是6了 然后打印一次 不满足条件退出。。
所以正确写法是在while的同步代码块中再写一个while或if进行判断 如果不满足最外层while的条件就结束。

public void print1() throws InterruptedException {
        while (count<=n){
            //中断处
            synchronized (lock){
                if(count>n) break;
                System.out.println(count);
                count++;
            }
        }
    }

    public void print2() throws InterruptedException {
        while (count<=n){
            //可能中断处
            synchronized (lock){
                if(count>n) break;
                System.out.println(count);
                count++;
            }
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值