用多线程对文件进行读写效率要比用循环进行读写要给许多,接下来以创建100个文件并且写入字符串来测试。
首先用循环的方式进行:
public class FileMany {
static int name=200;
public static void main(String[] args) throws IOException {
long start = System.currentTimeMillis();
for(int i=0;i<100;i++) {
FileOutputStream out = new FileOutputStream(name+".txt");
name+=1;
FileChannel channel = out.getChannel();
ByteBuffer buffer = ByteBuffer.wrap(new String("lplp").getBytes());
channel.write(buffer);
channel.close();
}
long end = System.currentTimeMillis()-start;
System.out.println(end);
}
}
输出:140
多线程:
public class FileByThread implements Runnable{
static int name=1;
/*用同步锁是为了让文件名有序*/
Lock lock;
public FileByThread(Lock lock) {
this.lock=lock;
}
@Override
public