Note that when you use the runnable interface, you cannot directly create the object of the required class and run it. You must run it from an instance of the thread class. Many Program The runnable interface is preferred, because class hierarchy is imposed when the class is inherited from the Thread class. Code Example: Package Job;
ImportJava. Io. filewriter;
ImportJava. Io. ioexception;
ImportJava. util. date;
ImportJava. Text. simpledateformat;
Public class mainjob implements runnable {
private string path = null ;
PublicMainjob (string filepath ){
This. Path=Filepath;
}
Public Void Run (){
While ( True ){
Try {
Write ( " Write " + ( New Simpledateformat ( " Yyyymmddhhmmss " ). Format (( New Date ())));
Thread. Sleep ( 3000l );
} Catch (Interruptedexception e ){
Utils. log. Add ( This ). Error (E. getmessage ());
}
}
}
// When a lock is required, you only need to add synchronized before void.
Private Void Write (string MSG ){
Try {
String path = String. Format ( " % Slogs \ msg.txt " , This . Path );
Filewriter FW = New Filewriter (path, True );
FW. Write (string. Format ( " % S-% s \ r \ n " ,( New Simpledateformat ( " Yyyy-mm-dd hh: mm: SS " ))
. Format (( New Date (), MSG ));
FW. Flush ();
FW. Close ();
} Catch (Ioexception ex ){
Utils. log. Add ( This ). Error (ex. getmessage ());
}
}
}
Call in JSP
<%
String filepath = This. getservletcontext (). getrealpath ("/");
Thread job = new thread (New mainjob (filepath ));
Job. Start ();
%>