请帮忙看一下为什么下面的代码写入文件的内容与屏幕输出的不一样?
测试:
http://topic.csdn.net/u/20120803/10/6f16d665-4d2c-4ccb-8d16-74db1f36ed27.html?seed=1303139503&r=79321454#r_79321454
这个帖子发现了上述的问题。
我调试的时候稍微修改了一下,主要是在buff.write(str);后面加了一句:System.out.println("str is "+str);
发现题目所描述的问题。
代码如下:
import java.io.*;public class ThreadFight0 implements Runnable{ public void run() { long a = System.currentTimeMillis(); int i = 0; BufferedWriter buff = null; try { buff = new BufferedWriter(new FileWriter("d:\\logm2.txt")); } catch (IOException e1) { e1.printStackTrace(); } while (System.currentTimeMillis() - a <= 50) { try { String str = Thread.currentThread().toString() + i++; buff.write(str); System.out.println("str is "+str); buff.write("\r\n"); buff.flush(); } catch (IOException e) { e.printStackTrace(); } } try { buff.close(); System.err.println("OVER, and i is " + i); } catch (IOException e) { e.printStackTrace(); } } public static void main1(String[] args) { ThreadFight0 fight = new ThreadFight0(); Thread thread = new Thread(fight); thread.start(); } public static void main2(String[] args) { ThreadFight0 fight = new ThreadFight0(); ThreadFight0 fight2 = new ThreadFight0(); Thread thread2 = new Thread(fight2); Thread thread = new Thread(fight); thread.start(); thread2.start(); } public static void main(String[] args) { //main1(args); main2(args); }}