Implementation of Java Threads

Source: Internet
Author: User

A total of two methods the thread class and the Runnable interface, in contrast, tend to use runnable
Because a class can implement multiple interfaces, but can only inherit one class, it is relatively inclined to use runnable

The first method: use thread
is actually the way to inherit and rewrite the parent thread.
The basic idea is still Java's inherited polymorphic thought
The first is to write a class yourself, inherit the thread class, and rewrite the Run () method
Then implement the class that you write in the calling function, calling the Star () method
Note: Call the start () method to implement multi-threaded, call the Run () method, which is single-threaded

public class Firstthread extends thread{public void Run () {for (int i=1;i<100;i++) {System.out.println ("first thread-- > "+i);}}}

  

public class Main {public static void main (string[] args) {firstthread ft=new firstthread (), Ft.start (); for (int i=0;i<1 00;i++) {System.out.println ("main-->" +i);}}}

  

The second method: use runnable
is actually the implementation of the interface runnable
First realize the class that you write,
The thread object is then generated and the interface object as a parameter
Last start thread
Note: Call the start () method to implement multi-threaded, call the Run () method, which is single-threaded

public class Runable implements Runnable {@Overridepublic void Run () {for (int i=1;i<100;i++) {System.out.println (" First runnable--> "+i);}}}

  

public class Main {public static void main (string[] args) {//Implement Interface runable ra=new runable ();//Generate Thread object and interface object as parameter thread t =new thread (RA);//Start multithreaded T.start (); for (int i=0;i<100;i++) {System.out.println ("main-->" +i);}}}

  

Implementation of Java 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.