兩個線程,一個每分鐘寫入當前時間到指定文件,另一個線程讀出每分鐘新寫的內容。
使用簡單的Thread.sleep技術實現定時
package test.thread;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Date;
/**
* 多線程讀寫同一個文件的樣例。
*
* @author 趙學慶 www.java2000.net
*/
public class ThreadReadWrite {
public static void main(String[] args) {
new ThreadWrite().start();
try {
Thread.sleep(2000); // 休眠,以免那面還有寫好
} catch (InterruptedException e) {
e.printStackTrace();
}
new ThreadRead().start();
}
}
class ThreadWrite extends Thread {
File file = new File("test.txt");
@Override
public void run() {
try {
while (true) {
FileWriter out = new FileWriter(file, true);// 追加寫入
out.write(new Date() + "\n");
out.flush();
out.close();
Thread.sleep(3000); // 我這裡間隔改成3秒,方便測試
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ThreadRead extends Thread {
File file = new File("test.txt");
@Override
public void run() {
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
while (true) {
System.out.println(reader.readLine());
Thread.sleep(3000); // 我這裡間隔改成3秒,方便測試
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
如果真的要求嚴格,應該用Timer繼續比較精確的控制。
package test.thread;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
* 使用Timer定時器進行同一文件的讀寫。
*
* @author 趙學慶 www.java2000.net
*/
public class ThreadReadWriteTimer {
static File file = new File("test.txt");
public static void main(String[] args) {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
FileWriter out;
try {
out = new FileWriter(file, true);
// 追加寫入
out.write(new Date() + "\n");
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}, 0, 3000);
timer.scheduleAtFixedRate(new TimerTask() {
BufferedReader reader = null;
{
try {
reader = new BufferedReader(new FileReader(file));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
System.out.println(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}, 1000, 3000);
}
}