Implementation of 1.java single thread
public class Singletonthread { @SuppressWarnings ("static-access") public static void main (string[] args) {Thread T =t Hread.currentthread (); T.setname ("Singleton thread"); System.out.println (T.getname () + "Running"); for (int i=0;i<2000;i++) {System.out.println ("Thread is Sleeping:" +i), try {t.sleep (+);} catch (Interruptedexception e) { SYSTEM.OUT.PRINTLN ("The thread has gone wrong!! ");} } }}
2.java Multi-Threading implementation
① inherits the thread class and overrides the Run method
public class Threadimpl {public static void Main (string[] args) {Thread t1=new threadtest ("T1", 200); Thread t2=new threadtest ("T2", 100); Thread t3=new threadtest ("T3"); T1.start (); T2.start (); T3.start ();}} Class ThreadTest extends thread{private string name;private int ms;public threadtest (String name, int ms) {this.name = Nam e;this.ms = ms;} public void Run () {try {Sleep (ms)} catch (Interruptedexception e) {System.out.println ("Thread run interrupt exception");} SYSTEM.OUT.PRINTLN ("The thread called" +name+ "begins to hibernate" +ms+ "milliseconds");}}
Results:
The thread with the name T2 begins to sleep for 100 milliseconds, the thread that is called T1 begins to sleep 200 milliseconds, the thread that is called T3 begins to sleep 300 milliseconds
② implementing the Runnable interface, overriding the Run method
public class Runnableimpl {public static void main (string[] args) {runnabletest r1=new runnabletest (); Thread t=new thread (r1); T.start ();} } Class Runnabletest implements runnable{ @Overridepublic void Run () {//TODO auto-generated method stub}}
Java single-threaded and Java multi-threading implementations