首页 > 三个线程打印ABC,这样可以吗?
头像
rookie_chen
发布于 2021-07-18 08:39
+ 关注

三个线程打印ABC,这样可以吗?

public class test {
    public static volatile int flag1 = 1;
    public static volatile int flag2 = 0;
    public static volatile int flag3 = 0;
    public static void main(String[] args) {
        Thread t1 = new Thread(){
            @Override
            public void run() {
                while(true)
                {
                    if(flag1==1)
                    {
                        System.out.println("A");
                        flag1=0;
                        flag2=1;
                    }


                }
            }
        };
        Thread t2 = new Thread(){
            @Override
            public void run() {
                while(true)
                {
                    if(flag2==1)
                    {
                        System.out.println("B");
                        flag2=0;
                        flag3=1;
                    }

                }
            }
        };
        Thread t3 = new Thread(){
            @Override
            public void run() {
                while(true)
                {
                    if(flag3==1)
                    {
                        System.out.println("C");
                        flag3=0;
                        flag1=1;
                    }

                }
            }
        };

        t1.start();
        t2.start();
        t3.start();


    }
}
打印出来结果没错,不知这样是否可以?

全部评论

(3) 回帖
加载中...
话题 回帖

推荐话题

相关热帖

近期热帖

近期精华帖

热门推荐