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