2つのスレッドを交互に1~100印刷

5820 ワード

public class Solution2 {
    private static final Object lock = new Object();  //     

    private volatile int index = 1;           //        

    private volatile boolean aHasPrint = false;      //  A      

    class A implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 50; i++) {
                synchronized (lock) {
                    while (aHasPrint) {              //  A          
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("A:" + index);    //A        A  
                    index++;                   //      1
                    aHasPrint = true;             //  A     
                    lock.notifyAll();            //        
                }
            }
        }
    }

    class B implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 50; i++) {
                synchronized (lock) {
                    while (!aHasPrint) {               //  A        
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("B:" + index);  //  B  
                    index++;                 //    
                    aHasPrint = false;          //B             ,      A     
                    lock.notifyAll();          //      
                }
            }
        }
    }


    public static void main(String[] args) {
        Solution2 solution2 = new Solution2();
        Thread threadA = new Thread(solution2.new A());
        Thread threadB = new Thread(solution2.new B());
        threadA.start();
        threadB.start();
    }
}

関連コードhttps://github.com/LiWangCai/blogRelated自分で入手可能
転載先:https://www.cnblogs.com/liwangcai/p/10741644.html