Java Foundation---->java multi-threaded use (i)

Source: Internet
Author: User
Tags thread class

There are two ways to create Java threads, and here we learn through simple Examples.

multi-threading creation in Java one, creating multithreading by inheriting the thread class
 public classHellothreadextendsThread {@Override public voidRun () {Try{TimeUnit.SECONDS.sleep (1); System.out.println ("Hello from a thread!"); } Catch(interruptedexception E) {e.printstacktrace (); }    }     public Static voidMain (string[] Args)throwsinterruptedexception {hellothread Hellothread=NewHellothread ();        Hellothread.start (); System.out.println ("in Main thread."); }}

The results of the operation are as Follows:

 from a thread!

second, by implementing the Runnable interface to create multithreading
 public classHellorunnableImplementsRunnable {@Override public voidRun () {Try{System.out.println ("Hello from a thread!"); TimeUnit.SECONDS.sleep (1); } Catch(interruptedexception E) {e.printstacktrace (); }    }     public Static voidmain (string[] Args) {thread thread=NewThread (Newhellorunnable ());        Thread.Start (); System.out.println ("in Main method."); }}

The results of the operation are as Follows:

 from a thread!

Friendship Link

Java Foundation---->java multi-threaded use (i)

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.