001 Creating and starting a thread

Source: Internet
Author: User

I. Overview

There are two ways to create threads in Java,

[1] Inheriting thread, overriding the Run () method

[2] Implementation of the Runnable interface, the implementation of the run () method.

The advanced interface in Juc is actually done in either of these ways.

Two. Inherit thread to create threads.

 Public classCreateThread { Public Static voidMain (string[] args) {//Create a thread and complete the task one                NewThread () {@Override Public voidrun () {Task1 ();                                }}.start (); NewThread () {@Override Public voidrun () {task2 ();                };    }.start (); }     Public Static voidTask1 () { for(intI=0;i< -; i++) {            Try{TimeUnit.SECONDS.sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } System. out. println ("task1===>"+i); }    }     Public Static voidTask2 () { for(intI=0;i< -; i++) {            Try{TimeUnit.SECONDS.sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } System. out. println ("task2===>"+i); }    }}

Three. Implement the Runnable interface to create threads

 Public classuserunnable { Public Static voidMain (string[] args) {NewThread (NewRunnable () { Public voidrun () {Task1 ();                }}). Start (); NewThread (NewRunnable () { Public voidrun () {task2 ();    }}). Start (); }     Public Static voidTask1 () { for(intI=0;i< -; i++) {            Try{TimeUnit.SECONDS.sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } System. out. println ("task1===>"+i); }    }     Public Static voidTask2 () { for(intI=0;i< -; i++) {            Try{TimeUnit.SECONDS.sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } System. out. println ("task2===>"+i); }    }}

Four. Policy mode

In fact, there is only one way to create a thread, which is to create a thread object.

So what is the way we use the Runnable interface?

This is the use of a strategy model.

  

001 Creating and starting a thread

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.