Two implementation forms of Java threads

Source: Internet
Author: User

One, the first way to create a thread: Inherit the Thread class

classDemoextendsthread{@Override Public voidrun () {Super. Run ();  for(inti=0;i<20;i++) System.out.println (Thread.CurrentThread ()+"...."+i); }} Public classThreadDemo1 { Public Static voidMain (string[] args) {Demo D1=NewDemo (); Demo D2=NewDemo ();        D1.start ();    D2.start (); }}

Second way to create a thread: Implement the Runnable interface

classDemo2Implementsrunnable{ Public voidrun () { for(inti=0;i<20;i++) System.out.println (Thread.CurrentThread ()+"..."+i); }} Public classThreadDemo2 { Public Static voidMain (string[] args) {Thread T1=NewThread (NewDemo2 ()); Thread T2=NewThread (NewDemo2 ());        T1.start ();            T2.start (); }}

The advent of runnable is simply the encapsulation of the object of the thread's task.

Benefits of implementing the Runnable interface:

1. Separate the thread's tasks from the child classes of the thread for individual encapsulation. Encapsulates a task into an object based on object-oriented thinking.

2. Avoid the limitations of Java single inheritance

So the second method of creating threads is more common.

Two implementation forms of Java threads

Related Article

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.