002 Creation of Threads

Source: Internet
Author: User

One. Overview

There are two ways to create a thread, but in essence there is only one.

[1] inherits the thread, overriding the run () method.

[2] Implement the Runnable interface, overriding the run () method.

We can actually implement the Runnable method as a strategy model.

Two. Inheriting thread creating threads

@Test      Public void Test () {        new  Thread () {            publicvoid  run () {                  for (;;)                    System. out. println ("running .... ") " );            };        }. Start ();    }

Three. Implementing the Runnable Interface

@Test      Public void test2 () {        new Thread (new  Runnable () {            @Override            public void run () {                for(;;)                    System. out. println ("");            }        }). Start ();    }

Four. Compare

The only way a thread is created is to create a thread object and then start the thread, otherwise the new state's thread is actually not a real thread.

So, what about the Runnable interface?

The run () method is just a thread logical unit.

  We can understand that as a strategy pattern application, we create threads that are executing unused algorithms (policies).

Note: The start of a thread requires the invocation of JNI code, which means that the JVM is assigned a thread resource before it can be counted as a thread.

002 Creation of Threads

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.