Home > Java > javaTutorial > body text

Java multi-threading implementation methods revealed: How many do you know?

PHPz
Release: 2024-02-21 23:03:03
Original
740 people have browsed it

Java multi-threading implementation methods revealed: How many do you know?

Java multi-threading implementation methods revealed: How many do you know?

Introduction: Java multi-threading is an important means to improve program concurrency and efficiency. It is also an important knowledge point that is often asked in interviews. This article will introduce several common Java multi-threading implementation methods in detail, and provide corresponding code examples to help readers have a deeper understanding and mastery of multi-threading programming.

1. Inherit the Thread class

Inheriting the Thread class is one of the most basic and common implementation methods of Java multi-threading. Implement multi-threaded logic execution by customizing a subclass that inherits the Thread class and rewriting its run() method. The following is an example:

public class MyThread extends Thread {
    @Override
    public void run() {
        // 线程要执行的逻辑
    }

    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}
Copy after login

In this example, we customized a MyThread class, which inherits from the Thread class, and overrides the run() method. In the main method, we create a MyThread object and call its start() method to start the thread.

2. Implement the Runnable interface

Implementing the Runnable interface is another common way to implement multi-threading. Compared with inheriting the Thread class, implementing the Runnable interface is more flexible because Java allows a class to implement multiple interfaces at the same time, but does not allow inheritance of multiple classes. The following is an example:

public class MyRunnable implements Runnable {
    @Override
    public void run() {
        // 线程要执行的逻辑
    }

    public static void main(String[] args) {
        MyRunnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start();
    }
}
Copy after login

In this example, we define a MyRunnable class, which implements the Runnable interface and overrides the run() method. In the main method, we create a MyRunnable object and pass it to the constructor of the Thread class through the constructor, and then call the start() method to start the thread.

3. Use the Executor framework

Java provides the Executor framework for managing and executing threads in the thread pool. By using the Executor framework, we can more conveniently control the creation, destruction and execution of threads. The following is an example:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyExecutor {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    // 线程要执行的逻辑
                }
            });
        }
        executor.shutdown();
    }
}
Copy after login

In this example, we use the newFixedThreadPool() method provided by the Executors class to create a fixed-size thread pool, and then submit the task to the thread pool for execution through the execute() method. Finally, call the shutdown() method to close the thread pool.

4. Using Callable and Future

Callable and Future are new features introduced in Java 5, which are used to execute a task asynchronously and return a result. Unlike the Runnable interface, the call() method of the Callable interface can return a result and throw an exception. The following is an example:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class MyCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        // 线程要执行的逻辑
        return "Hello, World!";
    }

    public static void main(String[] args) {
        Callable<String> callable = new MyCallable();
        FutureTask<String> futureTask = new FutureTask<>(callable);
        Thread thread = new Thread(futureTask);
        thread.start();
        try {
            String result = futureTask.get();
            System.out.println(result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}
Copy after login

In this example, we define a MyCallable class, which implements the Callable interface and overrides the call() method. In the main method, we create a FutureTask object, pass it to the constructor of the Thread class, and then start the thread. Obtain the result of thread execution by calling the futureTask.get() method.

Conclusion:

This article introduces several common Java multi-threading implementation methods, including inheriting the Thread class, implementing the Runnable interface, using the Executor framework, and using Callable and Future. Through these sample codes, readers can have a clearer understanding of the characteristics and usage of various implementation methods. I hope this article can help readers learn and master Java multi-threaded programming more deeply.

The above is the detailed content of Java multi-threading implementation methods revealed: How many do you know?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!