多线程下file的锁
来源:互联网 发布:天际重制版捏脸数据 编辑:程序博客网 时间:2024/05/17 23:58
有的时候我们需要多线程的进行写文件,多线程的写入同一个文件会导致不安全问题,导致写入的结果混乱,必须要加锁,通过翻阅大牛的博客,发现FileLock可以胜任这种工作,自己做了个试验,整理了一下。
main
public class Main { public static void main(String[] args) throws IOException { File file = new File("/Users/20170220b/comment.txt"); for(int i=0;i<10;i++){ new Thread(new test1(file),"name"+i).start(); } }}
在main函数启动10个线程,传入一个文件的对象。
线程类
public class test1 implements Runnable { private File file; public test1(File file) { this.file = file; } public void run() { try { FileOutputStream out = new FileOutputStream(file, true); FileChannel channel = out.getChannel(); FileLock lock = null; while (true){ try { lock = channel.tryLock(); break; }catch (Exception e){ System.out.println("有其他线程正在操作该文件,当前线程休眠1000毫秒"); TimeUnit.MILLISECONDS.sleep(1000); } } out.write(Thread.currentThread().getName().getBytes()); out.write("...".getBytes()); out.write("***".getBytes()); lock.release(); channel.close(); out.close(); out=null; } catch (Exception e) { e.printStackTrace(); }finally { System.out.println(Thread.currentThread().getName()); } //不加锁的代码// try {// FileOutputStream out = new FileOutputStream(file, true);// out.write(Thread.currentThread().getName().getBytes());// out.write("...".getBytes());// out.write("***".getBytes());// out.close();// out=null;// } catch (Exception e) {// e.printStackTrace();// }finally {// System.out.println(Thread.currentThread().getName());// } }}
通过FileOutputStream写入文件,写入当前的线程名字,加上“—”,加上“*”,为了测试文件是否会出现混乱。
运行结果:
文件写入是混乱的。
然后给文件加锁之后:
文件写入按照我们希望的形式写入。
其实用logger会更加好一些,这种方式速度很慢
阅读全文
0 0
- 多线程下file的锁
- 多线程写不同的file
- 多线程下锁的总结
- 多线程和多核下“锁”的应用
- 多线程模型下的无锁编程
- linux下java的File
- net下的多线程
- linux下的多线程
- Android下的多线程
- Android下的多线程
- Android下的多线程
- linux下的多线程
- Android下的多线程
- .net下的多线程
- Android下的多线程
- Android下的多线程
- Android下的多线程
- Android下的多线程
- CSS八种方式实现等高布局
- np.arange函数
- 制作最小PE和ELF
- 音频编码——iOS VoiceConvert转码音频失真 & G729A
- 2017百度之星资格赛:1001. 度度熊保护村庄(计算几何+最小环)
- 多线程下file的锁
- Intellij idea 文件注释模板
- iOS 预处理语句
- 17-08-07 求最小公倍数
- 图片处理框架之picasso
- 科大讯飞文字合成语音 html5
- mongodb基础篇(三)上手的命令(未完待续。。。。)
- muse(musical.ly)音乐短视频去水印解析下载方法
- 使用jaxrs规范开发webservice(三)