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