一、读取文件

 package lock;

 import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.Calendar; public class ReadFileLock implements Runnable { public void run() {
try {
Calendar calstart = Calendar.getInstance();
Thread.sleep(5000);
File file = new File("D:/test.txt");
// 给该文件加锁
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
FileChannel fileChannel = randomAccessFile.getChannel();
FileLock fileLock = null;
while (true) {
try {
fileLock = fileChannel.tryLock();
break;
} catch (Exception e) {
System.out.println("有其他线程正在操作该文件,当前线程" + Thread.currentThread().getName() + "休眠1000毫秒");
Thread.sleep(1000);
}
}
byte[] buf = new byte[1024];
StringBuffer sb = new StringBuffer();
while ((randomAccessFile.read(buf)) != -1) {
sb.append(new String(buf, "utf-8"));
buf = new byte[850];
} System.err.println(sb.toString()); fileLock.release();
fileChannel.close();
randomAccessFile.close();
randomAccessFile = null; Calendar calend = Calendar.getInstance();
System.out.println("当前线程:" + Thread.currentThread().getName() + ",读文件共花了"
+ (calend.getTimeInMillis() - calstart.getTimeInMillis()) + "秒");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
} public static void main(String[] args) {
ReadFileLock threadTarget = new ReadFileLock();
Thread read = new Thread(threadTarget);
read.setName("thread-read-file");
read.start();
Thread read2 = new Thread(threadTarget);
read2.setName("thread-write-file2");
read2.start();
} }

二、写文件

package lock;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.Calendar; public class ReadFileLock implements Runnable { public void run() {
try {
Calendar calstart = Calendar.getInstance();
Thread.sleep(5000);
File file = new File("D:/test.txt");
// 给该文件加锁
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
FileChannel fileChannel = randomAccessFile.getChannel();
FileLock fileLock = null;
while (true) {
try {
fileLock = fileChannel.tryLock();
break;
} catch (Exception e) {
System.out.println("有其他线程正在操作该文件,当前线程" + Thread.currentThread().getName() + "休眠1000毫秒");
Thread.sleep(1000);
}
}
byte[] buf = new byte[1024];
StringBuffer sb = new StringBuffer();
while ((randomAccessFile.read(buf)) != -1) {
sb.append(new String(buf, "utf-8"));
buf = new byte[850];
} System.err.println(sb.toString()); fileLock.release();
fileChannel.close();
randomAccessFile.close();
randomAccessFile = null; Calendar calend = Calendar.getInstance();
System.out.println("当前线程:" + Thread.currentThread().getName() + ",读文件共花了"
+ (calend.getTimeInMillis() - calstart.getTimeInMillis()) + "秒");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
} public static void main(String[] args) {
ReadFileLock threadTarget = new ReadFileLock();
Thread read = new Thread(threadTarget);
read.setName("thread-read-file");
read.start();
Thread read2 = new Thread(threadTarget);
read2.setName("thread-write-file2");
read2.start();
} }

  

NIO读写文件并加锁的更多相关文章

  1. php读写文件要加锁

    http://www.bubuko.com/infodetail-241753.html

  2. JAVA NIO之文件通道

    1.简介 通道是 Java NIO 的核心内容之一,在使用上,通道需和缓存类(ByteBuffer)配合完成读写等操作.与传统的流式 IO 中数据单向流动不同,通道中的数据可以双向流动.通道既可以读, ...

  3. java输入输出 -- java NIO之文件通道

    一.简介 通道是 Java NIO 的核心内容之一,在使用上,通道需和缓存类(ByteBuffer)配合完成读写等操作.与传统的流式 IO 中数据单向流动不同,通道中的数据可以双向流动.通道既可以读, ...

  4. php中并发读写文件冲突的解决方案

    在这里提供4种高并发读写文件的方案,各有优点,可以根据自己的情况解决php并发读写文件冲突的问题. 对于日IP不高或者说并发数不是很大的应用,一般不用考虑这些!用一般的文件操作方法完全没有问题.但如果 ...

  5. php中并发读写文件冲突的解决方案(文件锁应用示例)

    PHP(外文名: Hypertext Preprocessor,中文名:“超文本预处理器”)是一种通用开源脚本语言.语法吸收了C语言.Java和Perl的特点,入门门槛较低,易于学习,使用广泛,主要适 ...

  6. Java读写文件的几种方式

    自工作以后好久没有整理Java的基础知识了.趁有时间,整理一下Java文件操作的几种方式.无论哪种编程语言,文件读写操作时避免不了的一件事情,Java也不例外.Java读写文件一般是通过字节.字符和行 ...

  7. 【自学php】第三天 - 读写文件

    这次的例子是把订单的数据保存起来,一般是用数据库来进行数据的存储最好,但是今天目的是为了学习读写文件,所以这次把数据存在文件里. 读写文件有一般有三个步骤: 1)打开文件.如果文件不存在,需要先创建它 ...

  8. Java NIO 读取文件、写入文件、读取写入混合

    前言 Java NIO(new/inputstream outputstream)使用通道.缓冲来操作流,所以要深刻理解这些概念,尤其是,缓冲中的数据结构(当前位置(position).限制(limi ...

  9. 分享十:php中并发读写文件冲突的解决方案

    对于日IP不高或者说并发数不是很大的应用,一般不用考虑这些!用一般的文件操作方法完全没有问题.但如果并发高,在我们对文件进行读写操作时,很有可能多个进程对进一文件进行操作,如果这时不对文件的访问进行相 ...

随机推荐

  1. MySQL 的日期类型有5个,分别是: date、time、year、datetime、timestamp。

    类型 字节 格式 用途 是否支持设置系统默认值 date 3 YYYY-MM-DD 日期值 不支持 time 3 HH:MM:SS 时间值或持续时间 不支持 year 1 YYYY 年份 不支持 da ...

  2. C语言 二维数组(指针)动态分配和释放(转)

    C 二维数组(指针)动态分配和释放 先明确下概念: 所谓32位处理器就是一次只能处理32位,也就是4个字节的数据,而64位处理器一次就能处理64位,即8个字节的数据.如果我们将总长128位的指令分别按 ...

  3. Hystrix 常用属性配置

    配置参数 默认值 说明 命令-执行属性配置 hystrix.command.default.execution.isolation.strategy THREAD 配置隔离策略,有效值 THREAD, ...

  4. 概率p输出1,概率1-p输出0,等概率输出0和1

    有个输出0和1的BIASED RANDOM,它以概率p输出1,以概率1-p输出0,以此RANDOM函数为基础,生成另一个RANDOM函数,该函数以1/2的概率输出1,以1/2的概率输出0 题目解答: ...

  5. Complexity and Tractability (3.44) - The Traveling Salesman Problem

    Copied From:http://csfieldguide.org.nz/en/curriculum-guides/ncea/level-3/complexity-tractability-TSP ...

  6. googletest--测试控制

    有时候如果某个测试出现了异常,但是我们想继续其他的测试怎么办. 最简单的方法就是,在测试的名字前加上"DISABLED_",如下面的例子所示: // Test with fixtu ...

  7. mac nginx 一些资料

    http://www.jianshu.com/p/918eb337a206 mac 的nginx 配置目录在/usr/local/etc/nginx 安装之前最好执行brew的update和upgra ...

  8. 学习笔记之WinSCP

    WinSCP :: Official Site :: Free SFTP and FTP client for Windows https://winscp.net/eng/index.php Win ...

  9. 学习笔记之pandas

    Python Data Analysis Library — pandas: Python Data Analysis Library https://pandas.pydata.org/ panda ...

  10. css文字链接滑过向上移动1像素

    方法一:行高 a{line-height:22px;} a:hover{line-height:21px;}   方法二:定位 a{position:absolute;top:0;} a:hover{ ...