4 ways to implement Java multi-threading

Source: Internet
Author: User
Tags thread class

1, inherit the thread class, rewrite the Run method;

 public  class  Thread01 extends   thread{ public   Thread01 () {}  public  void   run () {System.out.println (Thread.CurrentThread (). GetName (    ));  public  static  void   main (string[] args) {Thread01 thread01  = new   Thread01 ();        Thread01.setname ( "Inherits thread Class 1" 

2, implement the Runnable interface, override the Run method;

 public  class   Thread02 { public  static  void   main (string[] args) {S        Ystem.out.println (Thread.CurrentThread (). GetName ()); Thread t2  = new  Thread (new   MyThread02 ());     T2.start (); }}  class  MyThread02 implements  Span style= "COLOR: #000000" > runnable{@Override  public  void   run () {System.out.println (Thread.CurrentThread (). GetName () 
    + "2--implements the thread implementation of the Runnable interface" 

3, the implementation of the callable interface through the Futuretask wrapper to create thread threads;

4, creating threads through the thread pool;

 Public classTHREAD04 {Private Static intPool_num =10;  Public Static voidMain (string[] args)throwsinterruptedexception {executorservice executorservice= Executors.newfixedthreadpool (5);  for(inti = 0; i < Pool_num; i++) {Runnablethread runnable=NewRunnablethread ();        Executorservice.execute (runnable);    } executorservice.shutdown (); }}classRunnablethreadImplementsrunnable{@Override Public voidrun () {System.out.println ("4--threads created through the thread pool:" + thread.currentthread (). GetName () + ""); }  }  

4 ways to implement Java multi-threading

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.