用多线程对文件进行读写效率要比用循环进行读写要给许多,接下来以创建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 void run() {
try {
lock.lock();
FileOutputStream out = new FileOutputStream(name+".txt");
name+=1;
/*获得文件通道*/
FileChannel channel = out.getChannel();
/*创建一个字节缓冲区,将要写入文件的字符串放到该缓冲区*/
ByteBuffer buffer = ByteBuffer.wrap(new String("jdjjd").getBytes());
/*写入文件*/
channel.write(buffer);
/*关闭文件通道*/
channel.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws IOException {
/*创建一个容量为20的线程池*/
ExecutorService executorService = Executors.newFixedThreadPool(100);
Lock lock = new ReentrantLock();
/*或得程序开始执行的时间*/
long start = System.currentTimeMillis();
for(int i=0;i<100;i++) {
executorService.submit(new FileByThread(lock));
}
/*得到跑完整个程序所需要的时间*/
long end = System.currentTimeMillis()-start;
System.out.println(end);
}
}
输出:11
对比可见多线程效率高出许多