2015-11-05 43 views
2

創建的兩個線程誰能告訴我爲什麼synchronized關鍵字不起作用。無法同步在主要()

package Threading; 

class NewThreadt extends Thread { 

    synchronized void dota(int a){ 
     System.out.println(a); 
    } 

    // This is the entry point for the second thread. 
    public void run() { 
    try { 
     for(int i = 5; i > 0; i--) { 

     dota(i) ; 
     Thread.sleep(500); 
     } 
    } catch (InterruptedException e) { 
     System.out.println("Child interrupted."); 
    } 
    System.out.println("Exiting child thread."); 
    System.out.println(Thread.currentThread());  
    } 
} 

class abc { 
    public static void main(String args[]) { 
    NewThreadt t=new NewThreadt(); 
    NewThreadt q=new NewThreadt(); 
    t.start(); 
    q.start(); 


    System.out.println("Main thread exiting."); 
    } 
} 

輸出我對上述程序執行得到:

5 
5 
4 
4 
3 
3 
2 
2 
1 
1 

,我想輸出:

5 
4 
3 
2 
1 
5 
4 
3 
2 
1 
+0

標記的'DOTA()'方法如'synchronized'僅確保每次調用'DOTA()'塊的任何其他呼叫''NewThreadt'的同一個實例上的'dota()'。它不會遠程執行您認爲它所做的事情。 – khelwood

+0

爲什麼你使用線程,如果你想完全相應地? -_- – Suvitruf

+0

對包含完整的測試程序以說明問題的一個問題,其實際產出的樣本以及對預期產出的明確說明,恭喜並獲得滿意答覆。這種組合出奇的罕見。 –

回答

1

爲了得到你想要的東西,你需要兩個變化:

  1. 同步同一對象上的兩個線程。目前,他們每個人都在同步this
  2. 將同步置於run之外的循環中,以便一個線程在另一個線程進入之前完成整個循環。

這裏是您的NewThreadt類的修改版本:

class NewThreadt extends Thread { 

    private static Object lock = new Object(); 

    void dota(int a) { 
    System.out.println(a); 
    } 

    // This is the entry point for the second thread. 
    public void run() { 
    synchronized (lock) { 
     try { 
     for (int i = 5; i > 0; i--) { 

      dota(i); 
      Thread.sleep(500); 
     } 
     } catch (InterruptedException e) { 
     System.out.println("Child interrupted."); 
     } 
     System.out.println("Exiting child thread."); 
     System.out.println(Thread.currentThread()); 
    } 
    } 
}