Java single-threaded and Java multi-threading implementations

Source: Internet
Author: User

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

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.