Java thread creation methods and their comparison

Source: Internet
Author: User

Java thread creation methods and their comparison

There are three main ways to create a thread in Java:

1. inherit the Thread class to create a Thread class

(1) define the subclass of the Thread class and override the run method of the class. The method body of the run method represents the task to be completed by the Thread. Therefore, the run () method is called the execution body.

(2) create an instance of the Thread subclass, that is, create a Thread object.

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

Package com. thread; public class FirstThreadTest extends Thread {int I = 0; // rewrite the run method. The method body of the run method is the public void run () {(; I <100; I ++) {System. out. println (getName () + "" + I) ;}} public static void main (String [] args) {for (int I = 0; I <100; I ++) {System. out. println (Thread. currentThread (). getName () + ":" + I); if (I = 20) {new FirstThreadTest (). run (); new FirstThreadTest (). run ();}}}}

In the above Code, the Thread. currentThread () method returns the Thread object currently being executed. The GetName () method returns the name of the thread that calls the method.

2. Create a Thread class through the Runnable interface

(1) define the implementation class of the runnable interface and rewrite the run () method of the interface. The method body of the run () method is also the thread execution body of the thread.

(2) create a Runnable implementation class instance and use this instance as the Thread target to create a Thread object. This Thread object is the real Thread object.

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

The sample code is as follows:

Package com. thread; public class RunnableThreadTest implements Runnable {private int I; public void run () {for (I = 0; I <100; I ++) {System. out. println (Thread. currentThread (). getName () + "" + I) ;}} public static void main (String [] args) {for (int I = 0; I <100; I ++) {System. out. println (Thread. currentThread (). getName () + "" + I); if (I = 20) {RunnableThreadTest rtt = new RunnableThreadTest (); new Thread (rtt, "new Thread 1 "). start (); new Thread (rtt, "new Thread 2 "). start ();}}}}

3. Create a thread through Callable and Future

(1) Create an implementation class for the Callable interface and implement the call () method. The call () method will act as the thread execution body and return values.

(2) create an instance of the Callable implementation class and use the FutureTask class to wrap the Callable object. The FutureTask object encapsulates the return value of the call () method of the Callable object.

(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 obtain the returned value after the execution of the subthread ends.

Instance code:

Package com. thread; import java. util. concurrent. Callable; import java. util. concurrent. ExecutionException; import java. util. concurrent. FutureTask; public class CallableThreadTest implements Callable
 
  
{Public static void main (String [] args) {CallableThreadTest ctt = new CallableThreadTest (); FutureTask
  
   
Ft = new FutureTask <> (ctt); for (int I = 0; I <100; I ++) {System. out. println (Thread. currentThread (). getName () + "cyclic variable I value" + I); if (I = 20) {new Thread (ft, "Threads with returned values "). start () ;}try {System. out. println ("subthread return value:" + ft. get ();} catch (InterruptedException e) {e. printStackTrace ();} catch (ExecutionException e) {e. printStackTrace () ;}@ Overridepublic Integer call () throws Exception {int I = 0; for (; I <100; I ++) {System. out. println (Thread. currentThread (). getName () + "" + I);} return I ;}}
  
 

2. Comparison of three methods for creating threads

The advantages of using Runnable and Callable interfaces to create multiple threads are as follows:

The thread class only 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 process the same resource, thus separating the CPU, code, and data, the formation of a clear model better reflects the idea of object-oriented.

Disadvantages:

Programming is a little complicated. To access the current Thread, you must use the Thread. currentThread () method.

The advantages of using the method that inherits the Thread class to create multithreading are:

It is easy to write. If you need to access the current Thread, you do not need to use the Thread. currentThread () method to directly use this to obtain the current Thread.

Disadvantages:

The Thread class has inherited the Thread class, so it cannot inherit other parent classes.


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.