Two threads, one per minute writes the current time to the specified file, and the other thread reads the newly written content per minute.
Using simple Thread.Sleep technology to implement timing
Package Test.thread
Import java.io.BufferedReader;
import java.io.File;
Import Java.io.FileReader;
Import Java.io.FileWriter;
Import java.util.Date;
/**
* A sample that reads and writes the same file in multithreading.
*
* @author Zhaoqing www.java2000.net
*/
public class Threadreadwrite {
public static void Main (string[) args) {
New Threadwrite (). Start ();
try {
Thread.Sleep (2000);//hibernate, lest there should be written on that side
catch (Interruptedexception e) {
E.printstacktrace ()
New Threadread (). Start ();
}
}
Class Threadwrite extends Thread {
File = new file ("Test.txt");
@Override
public void Run () {
try {
while (true) {
FileWriter out = new FileWriter (file, true); /Append Write to
Out.write (new Date () + "\ n");
Out.flush ();
Out.close ();
Thread.Sleep (3000);//I change the interval here to 3 seconds to facilitate testing
} 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); I change the interval here to 3 seconds to facilitate testing of
}
catch (Exception e) {
E.printstacktrace ()
}
}