Java多线程写文件

通过对比测试,展示了在Java中使用多线程写文件相比于循环写入的显著效率提升。实验中创建了100个文件并写入字符串,结果显示多线程方式的性能优越。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用多线程对文件进行读写效率要比用循环进行读写要给许多,接下来以创建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

对比可见多线程效率高出许多


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值