Three ways to create threads in Java and compare them

Source: Internet
Author: User

There are three main ways of creating threads in Java:

First, 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.

Package Com.thread;public class Firstthreadtest extends thread{int i = 0;//rewrite the Run method, the method body of the Run method is the field execution body public void run () {for (; 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 ();}}}

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.

Second, create the thread class 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:

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 ();}}}

Iii. creating 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.

(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.

(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:

Package Com.thread;import Java.util.concurrent.callable;import Java.util.concurrent.executionexception;import Java.util.concurrent.futuretask;public class Callablethreadtest implements Callable<integer>{public static void Main (string[] args) {callablethreadtest CTT = new Callablethreadtest (); futuretask<integer> ft = new Futuretask<> (CTT), for (int i = 0;i < 100;i++) {System.out.println ( Thread.CurrentThread (). GetName () + "The value of the loop variable i" +i), if (i==20) {New Thread (ft, "thread 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 ();}} @Overridepublic Integer Call () throws Exception{int i = 0;for (; i<100;i++) {System.out.println (Thread.CurrentThread ( ). GetName () + "" +i); return i;}}

Ii. comparison of three ways to create threads

When using the runnable, callable interface to transcend multiple threads, 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.

The advantage of creating multiple threads with the inherited thread class is:

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.


Three ways to create threads in Java and compare them

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.