This is the ninth day of my participation in the First Challenge 2022. For details: First Challenge 2022.

In Java, there are seven ways to create a thread, divided into the following three categories:

  1. Thread class, which can be implemented in two ways.
  2. The Runnable interface is implemented in three ways.
  3. The Callable interface is implemented in two ways.

Let’s look at them one by one.

1. Inherit the Thread class

Inherit Thread class and rewrite the run method, is the earliest method to create a Thread, its implementation methods have the following two:

  1. Create a normal class that inherits Thread and overwrites the run method.
  2. Inherit and rewrite the run method using an anonymous inner class.

The concrete implementation is as follows.

1.1 Common Classes inherit Threads

Create a common class that inherits Thread and overwrites the run method, where the code in the run method is the specific business code to be executed by the Thread.

// A custom class inherits Thread and overwrites the run method
class MyThread extends Thread {
    @Override
    public void run(a) {
        // Add business methods...}}// Create thread and execute
public class ThreadExample {
    public static void main(String[] args) {
        // Create a thread
        Thread thread = new MyThread();
        // Start the threadthread.start(); }}Copy the code

1.2 Anonymous inner Classes

This is a bit cumbersome, but we can also use the following anonymous class:

// Create thread anonymously
Thread t1 = new Thread() {
    @Override
    public void run(a) {
        // Add business methods...}};// Start the thread
t1.start();
Copy the code

1.3 Weakness Analysis

The implementation of Thread has an obvious drawback. The Java language is single-inheritance, so if you inherit Thread, you cannot inherit other classes.

2. Implement the Runnable interface

In the Java language, multiple interfaces can be implemented, although multiple inheritance is not possible. Here are three ways to implement the Runnable interface:

  1. Create a normal class that implements the Runnable interface and override the Run method.
  2. Create the Runnable implementation class anonymously and override the Run method.
  3. Create anonymous Runnable implementation classes using Lambda (JDK 8+).

2.1 Common classes implement Runnable

// Define a common class that implements the Runnable interface
class MyRunnable implements Runnable {
    @Override
    public void run(a) {
        // Add business methods...}}// Thread creation
public static void main(String[] args) {
    // Create a Runnable implementation class
    MyRunnable myRunnable = new MyRunnable();
    // Create a thread
    Thread thread = new Thread(myRunnable);
    // Start the thread
    thread.start();
}
Copy the code

2.2 Anonymous Runnable implementation classes

// Anonymous Runnable implementation class
Thread t2 = new Thread(new Runnable() {
    @Override
    public void run(a) {
        // Add business methods...}});// Start the thread
t2.start();
Copy the code

Lambda creates Runnable

After JDK 8 (including JDK 8), we can use Lambda expressions to create threads, as shown in the following code:

// Use Lambda anonymous Runnable
Thread t3 = new Thread(() -> {
    // Add business methods...
});
// Start the thread
t3.start();
Copy the code

As you can see from the above code, using Lambda is recommended for programs with JDK 1.8 and older that do not require thread results because it is concise enough.

2.4 Weakness Analysis

All of the above thread creation methods have a common problem: they do not get the results of the thread’s execution.

3. Use the Callable interface

JDK 1.5 introduced the Callable interface, to solve the previous can not get the results of thread execution embarrassment, it is implemented in the following two ways:

  1. Create a generic class that implements the Callable interface and override the Call method.
  2. Create an implementation class for Callable using an anonymous inner class and override the Call method.

3.1 Common classes implement Callable

// Define a common implementation of the Callable interface that returns a result of type Integer.
class MyCallable implements Callable<Integer> {
    @Override
    public Integer call(a) throws Exception {
        // Business implementation code...
        return 0; }}// Create a thread
public static void main(String[] args) throws ExecutionException, InterruptedException {
    // Create a generic Callable class
    MyCallable callable = new MyCallable();
    // Use FutureTask to get thread execution results
    FutureTask<Integer> futureTask = new FutureTask<>(callable);
    // Create a thread
    Thread thread = new Thread(futureTask);
    // Start the thread
    thread.start();
    // Get the result of thread execution
    int result = futureTask.get();
}

Copy the code

The code above uses FutureTask + Callable to get the result of the thread’s execution. It can accept any type of return value. We just need to define the data type to return when we create the Callable implementation class.

3.2 Anonymous Callable implementation class

// FutureTask is used to get the result of thread execution
FutureTask<Integer> futureTask = new FutureTask<>(new Callable<Integer>() {
    @Override
    public Integer call(a) throws Exception {
        // Business code...
        return 0; }});// Create a thread
Thread thread = new Thread(futureTask);
// Start the thread
thread.start();
// Get the result of thread execution
int result = futureTask.get();
Copy the code

conclusion

In the Java language, there are three classes of implementation methods for creating threads, and seven implementation methods. If JDK 1.8 or higher, we recommend Lambda to create threads without obtaining the results of thread execution, because it is concise enough. If you want to get thread results, you can use FutureTask + Callable to do so.

Judge right and wrong from yourself, praise to listen to others, gain and loss in the number.

Public number: Java interview analysis

Interview collection: gitee.com/mydb/interv…