One Java thread: two methods to implement one thread

Source: Internet
Author: User

Java uses the java. Lang. Thread class to implement multithreading. Let's take a look at the two methods of thread creation and running through the same example:
(1) One is to declare the sub-class of thread, and to overload the Thread class method run (extend java. Lang. Thread and override the run method)

class MyThread extends Thread{public void run(){for(int row = 1;row <5;row ++){for(int i = 0;i < 5;i ++)System.out.print('*');System.out.println();}}}public class TestNew {public static void main(String[] args) {// TODO Auto-generated method stubMyThread mt = new MyThread();mt.start();}}

Execution result:

*****
*****
*****
*****

(2) Another way is to declare a class that implements the runnable interface. Then implement the run (implement java. Lang. runnable and implement the run method) method)

class MyThread implements Runnable{public void run(){for(int row = 1;row <5;row ++){for(int i = 0;i < 5;i ++)System.out.print('*');System.out.println();}}}public class TestNew {public static void main(String[] args) {// TODO Auto-generated method stubThread myThread = new Thread(new MyThread());myThread.start();}}

The running result is the same as above. It should be noted that the thread itself only executes once, unless there is a circular Processing Mechanism in it.

 

Http://blog.csdn.net/duoshanx/archive/2004/08/28/87279.aspx ()

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.