Java multi-thread usage

Source: Internet
Author: User

I have never been too familiar with Thread multithreading. I learned some things today. Could you please share with me ~ To implement multithreading in Java, there are two methods: Inheriting the Thread class and implementing the Runable interface. For directly inheriting the Thread class, the general framework of the code is: [java] class name extends Thread {method 1; method 2 ;... Public void run () {// other code...} Attribute 1; Attribute 2 ;...} Here is a simple small example to help you understand it ~ The clock is output once every 1 s: [java] 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. printS TackTrace () ;}}} output result :.... endless output .... note: although the start () method is called here, the main body of the run () method is actually called. So: Why can't we directly call the run () method? In my understanding, the running of a thread requires support from the local operating system. However, this method has its drawbacks. In this example, ClockThread cannot be used if it has other parent classes. Because Java does not allow several parent classes at the same time. The following describes the following method: to implement the Runnable interface, the general framework is: [java] class name implements Runnable {method 1; method 2 ;... Public void run () {// other code...} Attribute 1; Attribute 2 ;...}

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.