Multithreading (Java)

Source: Internet
Author: User

Thread class and Runner interface

There are two ways to implement multithreading in Java

    • Inherit the Thread class
      Pros: You can change the behavior of threads by overriding the thread class's methods.
    • Implementing the Runner Interface
      Pros: You do not need to inherit the thread class, you can inherit other classes.
Package Threads.samples3; Public classThreadTest { Public Static void Main(string[] args) {//Create an instance of the Thread subclassThread1 T1 =New Thread1();//Create an instance of a class that implements the Runnable interface, passing it as a parameter to an instance of the Thread classThread t2 =NewThread (New Runnable1());//Start thread by calling the Start methodT1.Start(); T2.Start(); }}classThread1extendsThread {@Override     Public void Run() { for(inti =0; I <3; i++) {Try{Thread.Sleep( +); }Catch(Interruptedexception e) {e.Printstacktrace(); } System. out.println(i +"in Thread1"); }    }}classRunnable1ImplementsRunnable {@Override     Public void Run() { for(inti =0; I <3; i++) {Try{Thread.Sleep( +); }Catch(Interruptedexception e) {e.Printstacktrace(); } System. out.println(i +"in Runnable1"); }    }}/*0 in Thread10 in Runnable11 in Runnable11 in Thread12 in Runnable12 in Thread1*/

Multithreading (Java)

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.