無聊,寫了一個多線程同時讀寫檔案,當然同一時刻只有一個線程讀或者寫檔案
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();} }