Java多線程與並發庫進階應用程式-傳統線程同步通訊技術

來源:互聯網
上載者:User

標籤:資料   bool   ide   catch   資源   false   dmi   tor   cep   

面試題:

子線程迴圈10次,接著主線程迴圈100次,接著又回到子線程迴圈10次,接著又 主線程迴圈100次,如此迴圈50次,請寫出程式

/** * 子線程迴圈10次,接著主線程迴圈100次,接著又回到子線程迴圈10次,接著又 主線程迴圈100次,如此迴圈50次,請寫出程式 *  * @author Administrator *  */public class TraditionalThreadCommunication {    public static void main(String[] args) {        final Business business = new Business();        new Thread(new Runnable() {            @Override            public void run() {                for (int i = 1; i <= 50; i++) {                    business.sub(i);                }            }        }).start();        for (int i = 1; i <= 50; i++) {            business.main(i);        }    }}class Business {    private boolean isShoudeSub = true;    /**     * 同步加在需要訪問的資源的代碼上,不要放線上程上     * @param i     */    public synchronized void sub(int i) {        while (!isShoudeSub) {   //這裡也可以用 if ,用while比較好一些  As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop            try {                // 防止線程有可能被假喚醒 (while放在這裡提現了水準)                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        for (int j = 1; j <= 100; j++) {            System.out                    .println("sub thread sequence of " + j + ", loop of " + i);        }        isShoudeSub = false;        this.notify();    }    public synchronized void main(int i) {        while (isShoudeSub) {            try {                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        for (int j = 1; j <= 10; j++) {            System.out.println("main thread sequence of " + j + ", loop of "                    + i);        }        isShoudeSub = true;        this.notify();    }    /**     *      * synchronized (obj) { 這裡的obj與obj.wait必須相同,否則會拋異常         while (<condition does not hold>)             obj.wait();         ... // Perform action appropriate to condition     }     */}

 

要用到共同資料(包括同步鎖)或共同演算法的若干個方法應該歸在同一個類身上,這種設計正好提現了高類聚和程式的健壯性。

 

Java多線程與並發庫進階應用程式-傳統線程同步通訊技術

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.