子線程和主線程業務依次執行循環50次


子線程業務:循環10次
java

主線程業務:循環20次算法


這兩個循環(業務)須要交替執行共50次
app


要用到共同數據的(包括同步鎖)或共同算法(加密解密)的若干個方法應該歸在同一個類上,這種設計正好體現了高內聚和程序的健壯性
ide


 while (bShouldSub) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

中使用while防止假喚醒,使用if就不行oop

虛假喚醒就是一些obj.wait()會在除了obj.notify()和obj.notifyAll()的其餘狀況被喚醒,而此時是不該該返回的,因此要加條件判斷。this

synchronized (obj) {  
         while (<condition does not hold>)  
             obj.wait();  
         ... // Perform action appropriate to condition  
     }


public class TraditionalThreadCommunication {
    final Business business = new Business();

    public static void main(String[] args) {

            new TraditionalThreadCommunication().init();
        
    }

    private void init()  {

        new Thread(new Runnable() {

            @Override
            public void run() {

                for (int i = 0; i <= 50; i++) {

                    business.sub(i);

                }
            }
        }).start();

        for (int i = 0; i <= 50; i++) {

            business.main(i);
        }

    }

    //業務對象
    class Business {
        private boolean bShouldSub = true;

        public synchronized void sub(int i) {
            while (!bShouldSub) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            for (int j = 1; j <= 10; j++) {

                System.out.println("sub thread sequence of" + j + ",loop of "
                        + i);
            }
            bShouldSub = false;
            this.notify();
        }

        public synchronized void main(int i) {

            while (bShouldSub) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            for (int j = 1; j <= 20; j++) {

                System.out.println("main thread sequence of" + j + ",loop of "
                        + i);
            }

            bShouldSub = true;
            this.notify();
        }

    }

}


使用lock和condition改寫代碼加密

http://tianxingzhe.blog.51cto.com/3390077/1716805
線程

相關文章
相關標籤/搜索