Three ways to create threads in Java and compare them

Source: Internet
Author: User
Tags thread class

One, there are three main ways to create threads in Java: 1. Inherit the thread class to create a threading class

(1) Define a subclass of the thread class and override the Run method of the class, which represents the task that the thread will complete. So the run () method is called the actuator.

(2) Create an instance of the thread subclass, that is, the threading object is created.

(3) Call the Start () method of the thread object to start the thread.

 PackageCom.thread;  Public classFirstthreadtestextendsthread{inti = 0; //rewrite the Run method, the method body of the Run method is the field execution body     Public voidrun () { for(; i<100;i++) {System.out.println (GetName ()+"  "+i); }      }       Public Static voidMain (string[] args) { for(inti = 0;i< 100;i++) {System.out.println (Thread.CurrentThread (). GetName ()+"  : "+i); if(i==20)              {                  Newfirstthreadtest (). Start (); Newfirstthreadtest (). Start (); }          }      }  } 

The Thread.CurrentThread () method in the preceding code returns the currently executing thread object. The GetName () method returns the name of the thread that called the method.

2. Creating thread classes through the Runnable interface

(1) Define the implementation class for the Runnable interface, and override the run () method of the interface, which is also the thread execution body of the thread of the Run () method.

(2) Create an instance of the Runnable implementation class, and use this instance as the target of the thread to create the thread object, which is the true thread object.

(3) Call the Start () method of the thread object to start the thread.

The sample code is:

 PackageCom.thread;  Public classRunnablethreadtestImplementsRunnable {Private inti;  Public voidrun () { for(i = 0;i <100;i++) {System.out.println (Thread.CurrentThread (). GetName ()+" "+i); }      }       Public Static voidMain (string[] args) { for(inti = 0;i < 100;i++) {System.out.println (Thread.CurrentThread (). GetName ()+" "+i); if(i==20) {runnablethreadtest RTT=Newrunnablethreadtest (); NewThread (RTT, "New Thread 1"). Start (); NewThread (RTT, "New Thread 2"). Start (); }          }      }   }  

The execution process of a thread is simple, and when code start () executes, the Void run () that is overridden in the object is executed, and the thread dies after the method executes.

3. Create threads through callable and future

(1) Create an implementation class for the callable interface and implement the call () method, which will act as the thread execution body and have a return value.

 Public Interface  throws  Exception;}

(2) Create an instance of the callable implementation class, using the Futuretask class to wrap the callable object, which encapsulates the return value of the call () method of the Callable object. (Futuretask is a wrapper that is created by accepting callable, which implements both the future and the Runnable interface. )

(3) Use the Futuretask object as the target of the thread object to create and start a new thread.

(4) Call the Get () method of the Futuretask object to get the return value after the child thread execution ends

Instance code:

 PackageCom.thread; Importjava.util.concurrent.Callable; Importjava.util.concurrent.ExecutionException; ImportJava.util.concurrent.FutureTask;  Public classCallablethreadtestImplementsCallable<integer>  {         Public Static voidMain (string[] args) {callablethreadtest CTT=Newcallablethreadtest (); Futuretask<Integer> ft =NewFuturetask<>(CTT);  for(inti = 0;i < 100;i++) {System.out.println (Thread.CurrentThread (). GetName ()+ "The value of the loop variable i" +i); if(i==20)              {                  NewThread (FT, "threads with return value")). Start (); }          }          Try{System.out.println ("The return value of the child thread:" +ft.get ()); } Catch(interruptedexception e) {e.printstacktrace (); } Catch(executionexception e) {e.printstacktrace (); }} @Override PublicInteger Call ()throwsException {inti = 0;  for(; i<100;i++) {System.out.println (Thread.CurrentThread (). GetName ()+" "+i); }          returni; }    }  
Ii. comparison of three ways to create threads

1, when creating multi-threading in a way that implements Runnable, callable interfaces,

The advantages are:

The thread class simply implements the Runnable interface or callable interface and can inherit other classes.

In this way, multiple threads can share the same target object, so it is very suitable for multiple identical threads to handle the same resource, so that the CPU, code and data can be separated to form a clear model, which is a good embodiment of object-oriented thinking.

Disadvantages are:

Programming is slightly more complex, and you must use the Thread.CurrentThread () method if you want to access the current thread.

2. When you create a multi-threaded method with the inherited thread class,

The advantages are:

Writing is simple and if you need access to the current thread, you do not need to use the Thread.CurrentThread () method to get the current thread directly using this.

Disadvantages are:

The thread class has inherited the thread class, so it is no longer possible to inherit other parent classes.

3. The difference between runnable and callable

(1) The method of callable (rewriting) is call (), and the method of runnable (overriding) is run ().

(2) callable can return a value after a task is executed, and Runnable's task cannot return a value.

(3) Call method can throw an exception, the Run method can not.

(4) Run the callable task to get a future object that represents the result of an asynchronous calculation. It provides a way to check whether the calculation is complete, to wait for the completion of the calculation, and to retrieve the results of the calculation. The future object enables you to understand task execution, cancel the execution of a task, and get execution results.

Three ways to create threads in Java and compare them

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.