Java Multithreading Basics

Source: Internet
Author: User

1.thrtest.java inheriting the thread class mode

 Public classThrtestextendsThread {PrivateString name;  Publicthrtest () {} Publicthrtest (String name) { This. Name =name; }      Public voidrun () { for(inti = 0; I < 5; i++) {System.out.println (name+ "Run" +i); }    }      Public Static voidMain (string[] args) {thrtest H1=NewThrtest ("A"); Thrtest H2=NewThrtest ("B");//H1.run ();//H2.run ();H1.start ();    H2.start (); }}

2.runntest.java Implement Runnable interface mode

 Public classRunntestImplementsRunnable {PrivateString name;  Publicrunntest () {} Publicrunntest (String name) { This. Name =name; }        Private intTicket = 5;//5 Tickets         Public voidrun () { for(inti=0; i<=20; i++) {            if( This. ticket > 0) {System.out.println ( This. Name + Thread.CurrentThread (). GetName () + "Selling tickets" + This. ticket--); }        }    }        Public Static voidMain (string[] args) {runntest H1=NewRunntest ("Thread A");//resource Sharing//thread demo= New Thread (H1, "window number 1th");//thread demo1=new Thread (H1, "window number 2nd");//thread demo2=new Thread (H1, "window number 3rd");Thread Demo=NewThread (H1); Thread Demo1=NewThread (H1); Thread Demo2=NewThread (H1);        Demo.start ();        Demo1.start (); System.out.println ("---before thread starts" +demo2.isalive ());        Demo2.start (); System.out.println ("---After thread start" +demo2.isalive ()); }}

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.