Java实现多线程轮流打印1-100的数字

 思路:因为要打印1-100的数字,所以需要一个变量来记录打印到哪里,这个变量就是 i 。三个线程共享这个 i ,所以需要考虑多线程情况下,输出结果是否正确。

首先要保证任意一个线程对 i 进行修改都是对其它线程可见的,所以可以使用volatile进行修饰。

其次,对 i 进行+1的操作并不具有原子性,而volatile也无法保证原子性,所以需要加锁来保证 i +1是原子的。

因此就增加一个变量flag,也是volatile修饰,用flag来控制接下来的代码是否可以被执行,比如:程序刚一启动,flag=0,说明只有线程1可以执行,其它线程在判断flag值的时候发现为0,就不会进入接下来的代码块中,而线程1就可以 i++了,执行完再修改flag的值,使得其它线程可以继续执行。所以,flag变量就像一把锁,保证了 i++的原子性。

public class Solution {

    public static void main(String[] args) throws InterruptedException {
        new Solution().runThread();
    }

    private volatile int i=0;
    private Thread thread1,thread2,thread3;
    private volatile int flag=0;
    public void runThread() throws InterruptedException{
        thread1=new Thread(new Thread1());
        thread2=new Thread(new Thread2());
        thread3=new Thread(new Thread3());
        thread1.start();
        thread2.start();
        thread3.start();
    }
    public class Thread1 implements Runnable{
        public void run() {
            while(i<=100){
                if(flag==0) {
                    System.out.println(Thread.currentThread().getName()+" "+i);
                    i++;
                    flag=1;
                }
            }
        }
    }

    public class Thread2 implements Runnable{
        public void run() {
            while(i<=100){
                if(flag==1){
                    System.out.println(Thread.currentThread().getName()+" "+i);
                    i++;
                    flag=2;
                }
            }
        }
    }

    public class Thread3 implements Runnable{
        public void run() {
            while(i<=100){
                if(flag==2){
                    System.out.println(Thread.currentThread().getName()+" "+i);
                    i++;
                    flag=0;
                }
            }
        }
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值