2014-02-22 48 views
0

我知道線程同步。但是在Merlin Hughes的Java Network Programming這本書的代碼中,寫了println方法在System.out上同步。我不明白如何在System.out上同步一個方法。瞭解Java中的方法同步

第二個問題我想問:println函數是重寫的方法,還是僅僅是這個代碼中的用戶定義的方法?

import java.io.*; 

public class SimpleOut { 

    public static void main(String[] args) throws IOException { 
     for (int i = 0; i < args.length; i++) { 
      println (args[i]); 
     } 
    } 

    public static void println(String msg) throws IOException { 
     synchronized (System.out) { 
      for (int i=0 ; i<msg.length(); i++) { 
       System.out.write(msg.charAt (i) & 0xff); 
      } 
      System.out.write('\n'); 
     } 
     System.out.flush(); 
    } 

} 
+1

您可以通過引用同步任何對象 - 您爲什麼期望'System.out'有所不同?而你的代碼中的'println'方法不能覆蓋任何東西 - 它是靜態的... –

+0

是system.out一個對象,如果是的話?是誰的對象?它是什麼時候創建的? 我向println提出重寫方法的原因是,println是一個預定義函數,請解釋 –

+0

請參閱system.out http://javapapers.com/core-java/system-out-println/ – NFE

回答

1

您可以通過任何對象/實例進行同步。 out是在類java.lang.System中聲明的類變量。

public final static PrintStream out 
0

同步是指您在指定的'資源'引用上執行的機制。 System.out也是這個資源。也有鏈接到帖子link

這也是非常好的博客,瞭解一些更難的東西在Java我正在閱讀它,當我有時間有很多有用的東西。 Java revisited