读写文件不会出现并发性?

honey_fansy 2015-03-16 11:01:57
最近需要把日志写在文本中,我需要测试有没有并发性,但测出来没有并发性,按道理不同线程写入文件肯定有并发性的。
下面是代码:

package com.dragon.util;

public class WriteLogThread implements Runnable {

private String fileName;
private int index;

public String getFileName() {
return fileName;
}

public void setFileName(String fileName) {
this.fileName = fileName;
}

public int getIndex() {
return index;
}

public void setIndex(int index) {
this.index = index;
}

@Override
public void run() {
for (int i = 0; i < 100; i ++) {
try {
WriteLogTool tool = WriteLogTool.instance;
tool.writeToFileB(fileName, "[id" + this.index + "][name" + this.index + "][" + "value" + this.index + "]" +
"[id" + this.index + "][name" + this.index + "][" + "value" + this.index + "]\n" );
} catch (Exception e) {
e.printStackTrace();
}
}
}

}




package com.dragon.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;

public enum WriteLogTool {

instance();
public void writeToFileA(String fileName, String record) throws IOException, InterruptedException {
//RandomAccessFile randomAccessFile = new RandomAccessFile(new File(fileName), "rws");
RandomAccessFile randomAccessFile = new RandomAccessFile(new File(fileName), "rw");
long fileLength = randomAccessFile.length();
randomAccessFile.seek(fileLength);
randomAccessFile.writeBytes(record + "\n");
randomAccessFile.close();
}
public void writeToFileB(String fileName, String record) throws IOException {
FileWriter writer = new FileWriter(fileName, true);
writer.write(record);
writer.close();
}

public static String logToString(Object object) {
String result = null;
return result;
}

public static void main(String[] args) {
String fileName = "D:\\1.txt";
File file = new File(fileName);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 100; i++) {
WriteLogThread thread = new WriteLogThread();
thread.setFileName(fileName);
thread.setIndex(i);
thread.run();
}
}

}



tool.writeToFileB(fileName, "[id" + this.index + "][name" + this.index + "][" + "value" + this.index + "]" +
"[id" + this.index + "][name" + this.index + "][" + "value" + this.index + "]\n" );
这一句我已经把字符串增加了好十几倍,让每一次写入文件的时间变长一点,但还是不会出现并发性的问题,为什么?
...全文
119 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

50,549

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧