多线程下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会更加好一些,这种方式速度很慢

原创粉丝点击