首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

System.out.println()为什么会影响到多线程?解决方案

2013-11-26 
System.out.println()为什么会影响到多线程?public class EvenCheckerEasy implements Runnable {private

System.out.println()为什么会影响到多线程?

public class EvenCheckerEasy implements Runnable {

private static int val = 0;

@Override
public void run() {
while (true) {
++val;
++val;
System.out.println(val); // 在我电脑上测试,此处添加打印输出似乎防止了并发的产生,为什么?
if (val % 2 != 0) {
System.out.println(val + " not event!");
return;
}
}
}

public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
exec.execute(new EvenCheckerEasy());
}
exec.shutdown();
}
}
多线程
[解决办法]
又是一个讨论离题的帖子,查下源代码就知道原因了。

public void println(int x) {
synchronized (this) {
    print(x);
    newLine();
}
}

热点排行