volatile关键字的使用:三个线程循环打印0-100

volatile关键字的使用:三个线程循环打印0-100,第1张

介绍

这是一道经典的面试题,我在面试的时候也用到过,这里分享一下volatile的用法。

volatile

volatile保证了变量的可见性,所以当我们使用volatile修饰一个变量时,其他线程可以立马感知,可以根据这个特点打印变量。

步骤

设置三个线程,实现Runnable接口,使用volatile修饰的变量count作为全局变量。每个线程对count进行判断,满足条件则打印.

public class Test {

    volatile static int count=0;

    static class Thread1 implements Runnable{

        @Override
        public void run() {
            int i=0;
            while (i<100){
                if(count%3==0){
                    System.out.println(Thread.currentThread().getName()+"打印"+i);
                    i+=3;
                    ++count;
                }
            }
        }
    }

    static class Thread2 implements Runnable{

        @Override
        public void run() {
            int i=1;
            while (i<100){
                if(count%3==1){
                    System.out.println(Thread.currentThread().getName()+"打印"+i);
                    // i+=3是下一次需要打印的值,下面同理
                    i+=3;
                    ++count;
                }
            }
        }
    }

    static class Thread3 implements Runnable{

        @Override
        public void run() {
            int i=2;
            while (i<100){
                if(count%3==2){
                    System.out.println(Thread.currentThread().getName()+"打印"+i);
                    i+=3;
                    ++count;
                }
            }
        }
    }

    public static void main(String[] args) {

        Thread t1 = new Thread(new Thread1());
        Thread t2 = new Thread(new Thread2());
        Thread t3 = new Thread(new Thread3());
        t1.start();
        t2.start();
        t3.start();

    }
}
结果

拓展

如果是两个线程,只需要把上面的i+=3改成i+=2,while循环也进行改变,最后删除一个线程即可。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/877756.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存