我知道線程同步。但是在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();
}
}
您可以通過引用同步任何對象 - 您爲什麼期望'System.out'有所不同?而你的代碼中的'println'方法不能覆蓋任何東西 - 它是靜態的... –
是system.out一個對象,如果是的話?是誰的對象?它是什麼時候創建的? 我向println提出重寫方法的原因是,println是一個預定義函數,請解釋 –
請參閱system.out http://javapapers.com/core-java/system-out-println/ – NFE