Three ways to create threads in Java and differences

Source: Internet
Author: User
Tags thread class

Java uses the thread class to represent threads, and all thread objects must be instances of the thread class or its subclasses. Java can create threads in three ways, as follows:

1) Inherit thread class to create threads

2) Implement runnable interface creation thread

3) Create threads using callable and future

Let's take a look at these three ways to create threads, respectively.

------------------------inherit the thread class to create threads---------------------

The general steps to create and start multithreading by inheriting the thread class are as follows

1 "D defines a subclass of the thread class and overrides the run () method of the class, which is the task that the thread needs to complete, and the run () method is also known as the thread executor.

2 "Creates an instance of the thread subclass, that is, the threading object is created

3 "Start thread, which is the start () method of the calling thread

Code instance

public class MyThread extends thread{//inherits the Thread class

public void Run () {

Overriding the Run method

}

}

public class Main {

public static void Main (string[] args) {

New MyThread (). Start ();//Create and start a thread

}

}

------------------------Implement the Runnable interface to create a thread---------------------

The general steps to create and start a thread by implementing the Runnable interface are as follows:

1 "Defines the implementation class for the Runnable interface, overriding the run () method, which is the same as the run () method in thread

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 real thread object

3 "The third part still starts the thread by invoking the start () method of the Thread object

code example:

public class MyThread2 implements Runnable {//Implement Runnable interface

public void Run () {

Overriding the Run method

}

}

public class Main {

public static void Main (string[] args) {

Create and start a thread

MyThread2 mythread=new MyThread2 ();

Thread thread=new thread (myThread);

Thread (). Start ();

or new Thread (new MyThread2 ()). Start ();

}

}

------------------------Create threads using callable and future---------------------

Unlike the Runnable interface, the callable interface provides a call () method as the thread execution body, and the call () method is more than the run () method function to be powerful.

The call () method can have a return value

The call () method declares an exception to be thrown

JAVA5 provides a future interface to represent the return value of the call () method in the callable interface, and provides an implementation class Futuretask for the future interface, which implements both the future interface and the Runnable interface. Therefore, it can be used as the target of the thread class. Several public methods have been defined in the future interface to control its associated callable tasks.

>boolean Cancel (Boolean mayinterruptifrunning): View cancels the callable task associated with the future

>v get (): Returns the return value of the call () method in callable, calling this method causes the program to block and must wait until the child thread ends to get the return value

>v Get (Long timeout,timeunit unit): Returns the return value of the call () method in callable, blocking the timeout time, and not returning the throw after a specified time timeoutexception

>boolean IsDone (): Returns True if the callable task is completed

>boolean iscancelled (): Returns True if the callable task is canceled before it is properly completed

After describing the related concepts, the steps to create and start a thread with a return value are as follows:

1 "Create an implementation class for the callable interface, implement the call () method, and then create an instance of the implementation class (from Java8 you can create the callable object directly using a lambda expression).

2 "uses the Futuretask class to wrap the callable object, which encapsulates the return value of the call () method of the Callable object

3 "Create and start a thread using the Futuretask object as the target of the thread object (because Futuretask implements the Runnable interface)

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

code example:

public class Main {

public static void Main (string[] args) {

MyThread3rd=new MyThread3 ();

Create a callable object using a lambda expression

Use the Futuretask class to wrap callable objects

Futuretask<integer> future=new futuretask<integer> (

(callable<integer>) ()->{

return 5;

}

);

New Thread (Task, "Thread with return value"). Start ();//essentially create and start a thread with a callable object

try{

System.out.println ("The return value of the child thread:" +future.get ()), the//get () method blocks until the child thread executes the end to return

}catch (Exception e) {

Ex.printstacktrace ();

}

}

}

--------------------------------------three ways to create threading comparisons--------------------------------------

The way to implement the runnable and implement the callable interface is basically the same, but the latter executes the call () method with a return value, the latter the thread execution body run () method has no return value, so you can classify the two methods in this way and the method of inheriting the thread class is as follows:

1, the thread just implements runnable or implements callable interface, also can inherit other classes.

2. In this way, multiple threads can share a target object, which is ideal for multithreaded processing of the same resource.

3, but programming is slightly more complex, if you need to access the current thread, you must call the Thread.CurrentThread () method.

4. Thread classes that inherit the thread class can no longer inherit from other parent classes (Java single inheritance decision).

Note: It is generally recommended to implement interfaces to create multithreading

Reference: https://www.cnblogs.com/3s540/p/7172146.html

Three ways to create threads in Java and differences

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.