Java multithreading 2

Source: Internet
Author: User
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 ();
%>

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.