java多線程有序讀取同一個文件
更新時間:2019年08月29日 14:14:48 作者:Changshu135
這篇文章主要為大家詳細介紹了java多線程有序讀取同一個文件,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本人剛參加工作,面試的時候遇四道筆試題,其中就有這道多線程有序讀取文件的題目,初看時拿不準(zhǔn),感覺會,又感覺不會。于是放棄了這道題,今天閑下來好好做一遍。
//定義一個runnable接口的實現(xiàn)類
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RunnableImpl implements Runnable{
//定義文件讀取的游標(biāo)位置
private static int now=0;
//定義即將被讀取的文件
static File file=new File("source/error.log");
//使用io包中的RandomAccessFile類,支持文件的隨機訪問
static RandomAccessFile raf=null;
//定義每次讀取的字節(jié)數(shù)
final static int len=256;
RunnableImpl() throws IOException{
raf=new RandomAccessFile(file, "rw");
}
@Override
public void run() {
while(true){
try {
//synchronized實現(xiàn)多線程的同步
synchronized (raf) {
//將文件內(nèi)容讀取到b字節(jié)數(shù)組中
byte[] b = new byte[len];
//設(shè)置游標(biāo)位置
raf.seek(now);
int temp=raf.read(b);
//如果沒讀取到,就結(jié)束線程
if(temp==-1){
return ;
}
//設(shè)置游標(biāo)偏移量
now+=temp;
//打印文件內(nèi)容
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();
}
文件內(nèi)容截圖

輸出結(jié)果:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot整合mybatisplus和druid的示例詳解
這篇文章主要介紹了SpringBoot整合mybatisplus和druid的方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-08-08
Spring Boot實現(xiàn)跨域訪問實現(xiàn)代碼
本文通過實例代碼給大家介紹了Spring Boot實現(xiàn)跨域訪問的知識,然后在文中給大家介紹了spring boot 服務(wù)器端設(shè)置允許跨域訪問 的方法,感興趣的朋友一起看看吧2017-07-07
Java?ThreadPoolExecutor線程池有關(guān)介紹
這篇文章主要介紹了Java?ThreadPoolExecutor線程池有關(guān)介紹,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-09-09
SpringBoot結(jié)合ElasticSearch實現(xiàn)模糊查詢的項目實踐
本文主要介紹了SpringBoot結(jié)合ElasticSearch實現(xiàn)模糊查詢的項目實踐,主要實現(xiàn)模糊查詢、批量CRUD、排序、分頁和高亮功能,具有一定的參考價值,感興趣的可以了解一下2024-03-03
Spring Security 中細化權(quán)限粒度的方法
這篇文章主要介紹了Spring Security 中細化權(quán)限粒度的方法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09

