当前位置: 移动技术网 > IT编程>开发语言>Java > java多线程有序读取同一个文件

java多线程有序读取同一个文件

2019年09月06日  | 移动技术网IT编程  | 我要评论

本人刚参加工作,面试的时候遇四道笔试题,其中就有这道多线程有序读取文件的题目,初看时拿不准,感觉会,又感觉不会。于是放弃了这道题,今天闲下来好好做一遍。

//定义一个runnable接口的实现类
import java.io.file;
import java.io.filenotfoundexception;
import java.io.ioexception;
import java.io.randomaccessfile;

public class runnableimpl implements runnable{
 //定义文件读取的游标位置
 private static int now=0;
 //定义即将被读取的文件
 static file file=new file("source/error.log");
 //使用io包中的randomaccessfile类,支持文件的随机访问
 static randomaccessfile raf=null;
 //定义每次读取的字节数
 final static int len=256;
 
 runnableimpl() throws ioexception{
 raf=new randomaccessfile(file, "rw");
 }
 @override
 public void run() {
 while(true){
 try {
 //synchronized实现多线程的同步
 synchronized (raf) {
 //将文件内容读取到b字节数组中
 byte[] b = new byte[len];
 //设置游标位置
 raf.seek(now);
 int temp=raf.read(b);
 //如果没读取到,就结束线程
 if(temp==-1){
  return ;
 }
 //设置游标偏移量
 now+=temp;
 //打印文件内容
 system.out.println(new string(b));
 }
 
 
 } catch (ioexception e) {
 // todo auto-generated catch block
 e.printstacktrace();
 }
 }
 
 }
}

运行程序,我使用了3个线程

public static void main(string[] args) throws ioexception {
 runnableimpl run=new runnableimpl();
 new thread(run).start();
 new thread(run).start();
 new thread(run).start();

 }

文件内容截图

输出结果:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网