多線程循環打印

前言

有很多中寫法,希望可以慢慢都寫出來。

思路

利用一個計數來除線程個數得到餘數從而控制線程輸出,並且利用一個Object的wait()和notify()方法來對線程的阻塞和喚醒,這裏的技巧可以看看。

  • wait()
    阻塞當前線程,等待被釋放,繼續執行當前線程
  • notify()
    喚醒監視該對象的第一個線程,notifyAll()喚醒監視該對象的所有線程。

代碼:


    static volatile int state; // 線程共有,判斷所有的打印狀態
    static final Object t = new Object(); // 線程共有,加鎖對象

/**
     * 改裝了一下
     */
    @Test
    public void mainSix() {
        state = 0;
        // 需要循環的次數
        int n = 3;
        int num = 2;

        new MyThread("A", 0, n, num).start();
        new MyThread("B", 1,  n, num).start();
    }


    class MyThread extends Thread {
        String name;
        int which; // 標示符:0:打印A;1:打印B;2:打印C
        int n; // 0:打印次數
        int num; // 循環週期


        public MyThread(String name,int which,int n,int num) {
            this.name = name;
            this.which = which;

            this.n = n;
            this.num = num;
        }

        @Override
        public void run() {
            for (int i = 0; i < n; i++) {
                synchronized (t) {
                    while (state % num != which) {
                        try {
                            t.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print(name); // 執行到這裏,表明滿足條件,打印
                    state++;
                    t.notify(); // 調用notifyAll方法
                }
            }
        }
    }

    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章