今天早上在公交车看《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" + " "); } } }
于是果断在eclipse中进入debug模式,采用单步调试就看到了问题的实质
当运行到system.out.println()函数时候,单步就进入代码如下
public void print(String s) { if (s == null) { s = "null"; } 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就一目了然。