今天早上在公交車看《java多線程設計模式》的時候,看到一個java多線程簡單輸出hello,world的問題,原始碼如下:
public class Mythread {public static void main(String[] args) {new ThreadTest().start();for (int i = 0; i < 100; i++) {System.out.print("world" + " ");}}}class ThreadTest extends Thread {public void run() {for (int i = 0; i < 100; i++) {System.out.print("hello" + " ");}}}
在console裡面輸出間斷的的 hello world···········world hello沒有問題,我突然想到為什麼不能輸出 hel wor......這樣間斷的輸出呢?
於是果斷在eclipse中進入debug模式,採用單步調試就看到了問題的實質
當運行到system.out.println()函數時候,單步就進入代碼如下
public void print(String s) {if (s == null) { s = "null";}write(s); }
我們再來看看write(s)方法
private void write(String s) {try { synchronized (this) {ensureOpen();textOut.write(s);textOut.flushBuffer();charOut.flushBuffer();if (autoFlush && (s.indexOf('\n') >= 0)) out.flush(); }}catch (InterruptedIOException x) { Thread.currentThread().interrupt();}catch (IOException x) { trouble = true;} }
public void write(String s, int off, int len) throws IOException {synchronized (lock) { ensureOpen(); int b = off, t = off + len; while (b < t) {int d = min(nChars - nextChar, t - b);s.getChars(b, b + d, cb, nextChar);b += d;nextChar += d;if (nextChar >= nChars) flushBuffer(); }}
看到synchronized就一目瞭然。