2014-01-16 120 views
-2

我使用完整的參考手冊學習Java。我現在在使用Multithreded Programming Concept。請幫助我瞭解此程序的執行步驟。需要幫助以瞭解程序

// This program is not synchronized. 
class Callme { 
    void call(String msg) { 
    System.out.print("[" + msg); 
    try { 
     Thread.sleep(1000); 
    } catch(InterruptedException e) { 
     System.out.println("Interrupted"); 
    } 
    System.out.println("]"); 
    } 
} 

class Caller implements Runnable { 
    String msg; 
    Callme target; 
    Thread t; 

    public Caller(Callme targ, String s) { 
    target = targ; 
    msg = s; 
    t = new Thread(this); 
    t.start(); 
    } 

    public void run() { 
    target.call(msg); 
    } 
} 

class Synch { 
    public static void main(String args[]) { 
    Callme target = new Callme(); 
    Caller ob1 = new Caller(target, "Hello"); 
    Caller ob2 = new Caller(target, "Synchronized"); 
    Caller ob3 = new Caller(target, "World"); 

    // wait for threads to end 
    try { 
     ob1.t.join(); 
     ob2.t.join(); 
     ob3.t.join(); 
    } catch(InterruptedException e) { 
     System.out.println("Interrupted"); 
    } 
    } 
} 

我不能理解邏輯也。

+0

@HighCore無法理解您的評論 – user3203399

+0

@HighCore Java還支持同步/等待設置,但是如果您願意,您也可以繼承Runnable類。無論如何,通常在Java中你只使用同步/等待,或者如果你正在存儲數據,你可能會使用volatile變量類型。 –

+0

@dylanlawrence **無處不在**附近['async/await'](http://msdn.microsoft.com/zh-cn/library/hh191443.aspx)/ continuation **語言級**支持在C#中。 –

回答

0

好吧,讓我們做這個碼的步驟一步的破敗:

第一,你有三類:呼我,來電顯示和同步。 您的主要方法是在Synch中,讓我們從它開始。 在實例化Callme的主要方法中,然後創建三個Caller對象。 現在,讓我們來看看來電構造:

public Caller(Callme targ, String s) { 
    target = targ; 
    msg = s; 
    t = new Thread(this); 
    t.start(); 
    } 

設置呼我,你傳遞給構造一個自定義字符串,然後創建一個新的線程,傳遞您剛纔創建爲參數的來電對象。

當您調用t.start時,您只需啓動另一個執行線程,該線程將與已運行的主線程並行運行。 此外,調用開始內部調用您在傳遞給線程構造函數的調用方對象中的run方法。 現在,當您實例化其他兩個呼叫者對象 並運行主要方法的其餘部分時,您的呼叫者線程將單獨運行。 instantianting 3級來電的對象後,主方法調用加入每個來電:

try { 
    ob1.t.join(); 
    ob2.t.join(); 
    ob3.t.join(); 
} catch(InterruptedException e) { 
    System.out.println("Interrupted"); 
} 

什麼加入要做的就是告訴主線程停止執行,等待這三個其他線程繼續之前停止執行。

現在,讓我們回到調用者運行方法,看看它會做什麼?

運行只是呼籲的CallMe參考方法調用你在構造函數中設置:

void call(String msg) { 
    System.out.print("[" + msg); 
    try { 
     Thread.sleep(1000); 
    } catch(InterruptedException e) { 
     System.out.println("Interrupted"); 
    } 
    System.out.println("]"); 
    } 

這裏您打印打印您傳遞作爲參數的自定義消息,使currrent線程睡眠至少1秒(它可能是更多的時間)在打印最後一個括號之前。

所以總結:在主要方法中,你創建三個調用者對象,並且每個創建一個Callme對象,並且當你執行main方法時(直到它到達了Thread.join方法),每個調用者線程執行它們自己的CallMe調用方法()的副本;