Java Multithreading (thread Class)

Source: Internet
Author: User

1. Multithreading

1. Multithreading implementation

There are two ways to achieve multithreading:

    • Inherit the Thread class, override the Run method, define the object, call the Start method
    • The Create class implements the Runnable interface, which is passed as an argument to the thread's construction method. Define the object and call the Start method.
1.1. Inherit Thread
    • Inheriting classes, overriding methods
classTDemo1extendsThread { PublicString name;//take a name for easy identification         PublicTDemo1 (String name) {//Construction Method         This. Name =name; } @Override Public voidRun () {//overriding the Run methodShow (); }     Public voidShow () {SYSTEM.OUT.PRINTLN (name+ ": Talk show Time"); }}
View Code
    • Create an object, call the Start method to start the thread
New TDemo1 ("Liang Hongda"new TDemo1 ("Li Chen Wei" new TDemo1 ("Wentao" new TDemo1 (" Td1.start (); Td2.start (); Td3.start (); Td4.start () ;
View Code

1.2. Implement Runnable
    • Implementing interfaces
classTDemo2ImplementsRunnable { PublicString name;//Identify         PublicTDemo2 (String name) {//Construction Method         This. Name =name; } @Override Public voidRun () {//Implementation MethodShow (); }    Private voidShow () {SYSTEM.OUT.PRINTLN (name+ "New Media broadcasting"); }    } 
View Code
    • Create object, Invoke method start
New Thread ( new TDemo2, New TDemo2 ("30 Seconds Car" new  Thread ( new TDemo2 ("Auto onion ring"new Thread (new TDemo2 ("Uncle said car"));        Td1.start (); Td2.start (); Td3.start (); Td4.start () ;
View Code

A

Java Multithreading (thread Class)

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.