Runnable interface and extended Thread class

Source: Internet
Author: User

Create a new class that can run threads in it. There are two ways: one is to expand the java. Lang. Thread class, and the other is to expand any class and implement the interface runnable.

 (1) Extend java. Lang. Thread class

Public class twothread extends thread {// when a new thread is started,ProgramThe entry is the run () method. From the time the run () method was just called to the time the run () method was just returned, the new thread was considered to be alive. // After the run () method returns, the thread disappears and cannot be restarted after the thread dies. Public void run () {for (INT I = 0; I <2; I ++) {system. out. println ("New thread") ;}} public static void main (string [] ARGs) {twothread TT = new twothread (); // a running thread is created for the new thread, first, you must build a new thread instance. TT. Start (); // The twothread object calls the START () method to start thread execution. The START () method inherits from the thread // the newly created thread can start execution (enter the run method) at any time after the start () method is called. This means that, before executing any statements after the start () method, the original thread may be swapped out. For (INT I = 0; I <2; I ++) {system. Out. println ("main thread ");}}}

The output may be as follows:

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.