java多線程間斷輸出刨根問底

來源:互聯網
上載者:User

今天早上在公交車看《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就一目瞭然。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.