多線程同時讀寫檔案

來源:互聯網
上載者:User

無聊,寫了一個多線程同時讀寫檔案,當然同一時刻只有一個線程讀或者寫檔案

import java.io.File;import java.util.Random;public class Test {     public static void main(String[] args) {         File file = new File("c:/test.txt");FileProcess fileObj = new FileProcess(file);String[] tempArray = null;for (int i = 0; i < 10; i++) {tempArray = new String[5];for (int j = 0; j < 5; j++) {tempArray[j] = System.currentTimeMillis() + "---" + new Random().nextInt(100);}ThreadWrite s1 = new ThreadWrite(fileObj, tempArray);new Thread(s1, "ThreadWrite-" + i).start();}for (int i = 0; i < 10; i++) {ThreadRead c1 = new ThreadRead(fileObj, null);new Thread(c1, "ThreadRead-" + i).start();}} } 

public class ThreadRead extends Thread {String[] tempSaved = null;FileProcess object;ThreadRead(FileProcess object, String[] tempSaved) {this.object = object;this.tempSaved = null;}public void run() {object.readFile(Thread.currentThread().getName());}}

public class ThreadWrite extends Thread {String[] tempSaved = null;FileProcess object ;ThreadWrite(FileProcess object, String[] tempSaved) {         this.object = object;         this.tempSaved = tempSaved; } public void run() {object.writeFile(Thread.currentThread().getName(), tempSaved);}}

import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;public class FileProcess {File file = null;    public String[] tempSaved;        FileProcess(File file) {     this.file = file;    } public synchronized void writeFile(String threadName, String[] tempSaved) {        FileWriter out = null;try {out = new FileWriter(file, true);// 追加寫入for (int i = 0; i < tempSaved.length; i++) {out.write(tempSaved[i] + "\r\n");}Thread.sleep(1000); } catch (Exception e) {e.printStackTrace();} finally {try {out.flush();out.close();} catch (IOException e) {e.printStackTrace();}}System.out.println(threadName + ": Have save File finished.");notifyAll();}     public synchronized void readFile(String threadName) {BufferedReader reader = null;try {reader = new BufferedReader(new FileReader(file));String tempString = null;while ((tempString = reader.readLine()) != null) {System.out.println(tempString);}} catch (Exception e) {e.printStackTrace();} finally {if (reader != null) {try {reader.close();} catch (IOException e1) {}}}System.out.println(threadName + ": have read file finished. ");notifyAll();} } 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.