A sample of multiple threads reading the same file at timed intervals

Source: Internet
Author: User
Tags current time sleep thread

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 ()
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.