How Java single-threaded and multithreaded implementations are implemented

Source: Internet
Author: User

Implementation of 1.java single thread

 Public classsingletonthread {@SuppressWarnings ("Static-access")     Public Static voidMain (string[] args) {Thread T=Thread.CurrentThread (); T.setname ("Singleton thread"); System.out.println (T.getname ()+ "Running");  for(inti=0;i<2000;i++) {System.out.println ("Thread is hibernating:" +i); Try{t.sleep (500); } Catch(interruptedexception e) {System.out.println ("There's a thread error!! "); }         }             }}

2.java Multi-Threading implementation

① inherits the thread class and overrides the Run method

 Public classThreadimpl { Public Static voidMain (string[] args) {Thread T1=NewThreadTest ("T1", 200); Thread T2=NewThreadTest ("T2", 100); Thread T3=NewThreadTest ("T3", 300);        T1.start ();        T2.start ();    T3.start (); }} classThreadTestextendsthread{PrivateString name; Private intMS;  PublicThreadTest (String name,intms) {                  This. Name =name;  This. Ms =MS; }          Public voidrun () {Try{sleep (ms); } Catch(interruptedexception e) {System.out.println ("Thread Run Interrupt exception"); } System.out.println ("The thread named" +name+ "begins to hibernate" +ms+ "milliseconds"); }} Result: A thread called T2 begins to sleep for 100 milliseconds the name of the T1 thread begins to sleep 200 milliseconds the name of the T3 thread begins to sleep 300 milliseconds

② implementing the Runnable interface, overriding the Run method

 Public classRunnableimpl { Public Static voidMain (string[] args) {runnabletest R1=Newrunnabletest (); Thread T=NewThread (R1);    T.start (); }     } classRunnabletestImplementsrunnable{@Override Public voidrun () {//TODO auto-generated Method Stub             }     }

How Java single-threaded and multithreaded implementations are implemented

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.