Android platform Java Multi-threading usage

Source: Internet
Author: User
Tags thread thread class

In Java to implement multithreading, there are two ways, one is to inherit the thread class, the other is to implement the Runable interface.

For the direct inheritance of the thread class, the code's general framework is:

Class Name extends thread{
Method 1;
Method 2;
...
public void Run () {
Other code ...
}
Property 1;
Property 2;
...

}
Here's a simple little example to help you understand

clock output every 1s time:

Import Java.util.Date;


public class Clockthreadtest {

public static void Main (string[] args) {
Clockthread clockthread=new Clockthread ();
Clockthread.start ();
System.out.println ("End");
}
}
Class Clockthread extends thread{
@Override
public void Run () {
Super.run ();
while (true) {
System.out.println (New Date ());
try {
Thread.Sleep (1000);
catch (Interruptedexception e) {
E.printstacktrace ();
}

}
}
}
The output results show:

....

The endless downward output ....

Note: While we are calling here the start () method, we actually call the body of the run () method.

So: Why can't we just call the run () method directly?

My understanding is that the operation of the thread requires the support of the local operating system.

But this method has its drawbacks, for example, clockthread if there are other parent classes, then this method can not be used. Because it is not allowed to have several parent classes at the same time in Java. The next method is described below:

By implementing the Runnable interface, the general framework is:

Class name implements Runnable{
Method 1;
Method 2;
...
public void Run () {
Other code ...
}
Property 1;
Property 2;
...

}

Related Article

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.