經典筆試題:3個線程連續打印XYZ


編寫代碼,使用3個線程,1個線程打印X,一個線程打印Y,一個線程打印Z,同時執行連續打印10次"XYZ"。

本題解題采用volatile實現,主要考察的點是volatile內存可見性問題。

public class Test {

    private static volatile Integer Count = 0;

    private static volatile Integer a = 0;

    public static void main(String[] args) {
        Thread one = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (a == 0) {
                        System.out.print("X");
                        a = 1;
                    }
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        });

        Thread two = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (a == 1) {
                        System.out.print("Y");
                        a = 2;
                    }
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        });

        Thread three = new Thread(new Runnable() {

            @Override
            public void run() {
                while (true) {
                    if (a == 2) {
                        System.out.println("Z");
                        a = 0;
                        Count++;
                        if(Count == 10) {
                            System.exit(0);
                        }
                    }
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        });

        one.start();
        two.start();
        three.start();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM