当前位置:网站首页>Three threads print digital demo alternately

Three threads print digital demo alternately

2022-06-13 00:49:00 Python's path to becoming a God

   The code is as follows , The notes are written in great detail , Copy and run .


public class Xs02 { 
    
    // use volatile Decorated two things that will be used for a while int
    private volatile int flag=0;
    private volatile int work=0;
    private Thread t1,t2,t3;

    public static void main(String[] args) { 
    
        Xs02 xs02 = new Xs02();
        // start-up 
        xs02.ts();
    }

    private void ts(){ 
    
        // How to start a thread , This step is written directly in main Method is OK 
        t1=new Thread(new a());
        t2=new Thread(new b());
        t3=new Thread(new c());
        t1.start();
        t2.start();
        t3.start();
    }
    private class a implements Runnable{ 
    
        @Override
        public void run() { 
    
            // First determine whether the number to be printed reaches the threshold , No, just continue printing 
            while (work<=100){ 
    
                // This is for volatile A special flag bit is made for each thread , Only when the variable is the specified value , Only the corresponding thread prints numbers 
                if(flag==0){ 
    
                    // Print the number if it is the specified value 
                    System.out.println("1:"+work++);
                    // After printing , Change to the flag bit of the next thread 
                    flag=1;
                }
            }
        }
    }

    private class b implements Runnable{ 
    
        @Override
        public void run() { 
    
            while (work<=100){ 
    
                if(flag==1){ 
    
                    System.out.println("2:"+work++);
                    flag=2;
                }
            }
        }
    }

    private class c implements Runnable{ 
    
        @Override
        public void run() { 
    
            while (work<=100){ 
    
                if(flag==2){ 
    
                    System.out.println("3:"+work++);
                    flag=0;
                }
            }
        }
    }
}

原网站

版权声明
本文为[Python's path to becoming a God]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280600498067.html