java多线程间断输出刨根问底

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




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值