Table of Contents
Five ways to create multi-threads in Java
(1) Inherit the Thread class
1. Implementation description
(1) Specific steps
(2) Code implementation
4. Note
(2) Implement the Runnable interface
(3) Implementing the Callable interface
(4) Inherit the TimerTask class
(3) Notes
(5) Start multi-threads through the thread pool
2. Implementation method
1) FixThreadPool(int n) fixed-size thread pool
2) SingleThreadExecutor() single-thread pool
3) CachedThreadPool() cache thread pool
4) ScheduledThreadPool(int n) scheduled periodic thread pool
5) Extension of WorkStealingPool() new thread pool class ForkJoinPool
Home Java javaTutorial What are the ways to create multi-threading in Java?

What are the ways to create multi-threading in Java?

Apr 26, 2023 pm 04:07 PM
java

What are the ways to create multi-threading in Java?


Five ways to create multi-threads in Java

(1) Inherit the Thread class

1. Implementation description

  • By inheriting Thread and overriding its run(), the tasks that need to be performed are defined in the run method. The created subclass can execute the thread method by calling the start() method.

  • By inheriting the thread class implemented by Thread, multiple threads cannot share the instance variables of the thread class. Different Thread objects need to be created, and resources are naturally not shared.

2. Specific steps

1) Define the UserThread class and inherit the Thread class
2) Override the run() method
3) Create a UserThread object
4) Call the start() method

3. Code implementation

What are the ways to create multi-threading in Java?
What are the ways to create multi-threading in Java?
What are the ways to create multi-threading in Java?

4. Note

  • Data resources are not shared, and multiple threads complete their own tasks. For example, if three ticket windows sell tickets at the same time, and each sells its own ticket, there will be a problem of three ticket windows selling the same ticket.

(2) Implement the Runnable interface

1. Implementation description

  • You need to first define a class to implement the Runnable interface and override the run() method of the interface. This run method is the thread execution body. Then create an object of the Runnable implementation class as the parameter target for creating the Thread object. This Thread object is the real thread object.

  • Using the thread class that implements the Runnable interface to create objects can realize resource sharing between threads.

2. Specific steps

1) Define a UserRun class and implement the Runnble interface
2) Override the run() method
3) Create an object of the UserRun class
4) Create an object of the Thread class, The object of the UserRun class is used as a parameter of the Thread class constructor
5) Start the thread

3. Code implementation

What are the ways to create multi-threading in Java?
What are the ways to create multi-threading in Java?
What are the ways to create multi-threading in Java?

4. Note

  • Data resource sharing, multiple threads complete a task together (multiple threads share the resources for creating thread objects). For example, three ticket windows (three threads) sell tickets at the same time (ticket in the MyThread class), and the three threads use resources together.

(3) Implementing the Callable interface

1. Implementation description

  • The Callable interface is like an upgraded version of the Runable interface. The call() method it provides will serve as the execution body of the thread and allows a return value.

  • Callable objects cannot be directly used as the target of Thread objects because the Callable interface is a new interface in Java5 and is not a sub-interface of the Runnable interface.

  • The solution to this problem is to introduce the Future interface. This interface can accept the return value of call(). The RunnableFuture interface is a sub-interface of the Future interface and the Runnable interface and can be used as a Thread The target of the object.

2. Specific steps

1) Define the class UserCallable and implement the Callable interface
2) Override the call() method
3) Create a UserCallable object
4) Create a subclass of FutureTask of the RunnableFuture interface Object, the parameter of the constructor is the object of UserCallable
5) Create an object of Thread class, the parameter of the constructor is the object of FutureTask
6) Start the thread

3. Code implementation

What are the ways to create multi-threading in Java?
What are the ways to create multi-threading in Java?
What are the ways to create multi-threading in Java?

4. Note

  • Data resource sharing, multiple threads complete a task together (multiple threads share the resources for creating thread objects). For example, three ticket windows (three threads) sell tickets at the same time (ticket in the MyThread class), and the three threads use resources together. At the same time, there will be a return value after the thread call is completed.

(4) Inherit the TimerTask class

1. Implementation description

  • The timer classes Timer and TimerTask can be used as another way to implement threads.

  • Timer is a threading facility used to schedule tasks for later execution in a background thread. The task can be scheduled to be executed once or repeatedly at regular intervals. It can be regarded as a timer and TimerTask can be scheduled.

  • TimerTask is an abstract class that implements the Runnable interface, so it has multi-threading capabilities.

2. Specific steps

1) Define the class UserTimerTask and inherit the abstract class TimerTask
2) Create an object of the UserTask class
3) Create an object of the Timer class and set the execution strategy of the task

3. Code implementation

What are the ways to create multi-threading in Java?
What are the ways to create multi-threading in Java?

What are the ways to create multi-threading in Java?

4. Notes

  • The thread created by the timer class is more used for the processing of scheduled tasks, and data resources are not shared between threads, and multiple threads complete their own tasks respectively.

(5) Start multi-threads through the thread pool

1. Implementation description

  • Thread pools can be created through the Executors tool class.

  • Improve the system response speed. When a task arrives, by reusing the existing thread, it can be executed immediately without waiting for the creation of a new thread.

  • Reduce system resource consumption and reduce the consumption caused by thread creation and destruction by reusing existing threads.

  • Conveniently control the number of concurrent threads. Because if threads are created without limit, it may cause OOM due to excessive memory usage, and may cause excessive CPU switching.

2. Implementation method

1) FixThreadPool(int n) fixed-size thread pool
(1) Specific steps

① Create a fixed-size thread through Executors.newFixedThreadPool(5) Pool
② Override the run( ) method of the Runnable class and use the thread pool to perform tasks
③ Shutdown( ) closes the thread pool

(2) Code implementation

What are the ways to create multi-threading in Java?
What are the ways to create multi-threading in Java?

(3) Notes
  • Create a fixed-size thread pool to share data resources and multiple threads to complete a task together .

2) SingleThreadExecutor() single-thread pool
(1) Specific steps

① Create a single-thread pool through Executors.newSingleThreadExecutor()
② Rewrite the run( ) method of the Runnable class and use the thread pool to perform tasks
③ Shutdown( ) to close the thread pool

(2) Code implementation

What are the ways to create multi-threading in Java?

(3) Notes
  • The thread pool only creates one thread to perform the task.

3) CachedThreadPool() cache thread pool
(1) Specific steps

① Create as many threads as possible through Executors.newCachedThreadPool() Pool
② Override the run( ) method of the Runnable class and use the thread pool to perform tasks
③ Shutdown( ) closes the thread pool

(2) Code implementation

What are the ways to create multi-threading in Java?
What are the ways to create multi-threading in Java?

(3) Notes
  • This method will create as many threads as possible to complete the task. For example, in the case, there are only 10 pictures. ticket, but the thread pool generated at least 12 threads.

4) ScheduledThreadPool(int n) scheduled periodic thread pool
(1) Specific steps

① Created by Executors.newScheduledThreadPool(5) A thread pool with a fixed number of core threads (minimum number of threads to maintain, threads will not be recycled after creation), and threads are executed regularly as planned.
② Rewrite the run( ) method of the Runnable class and use the thread pool to perform tasks
③ Shutdown( ) closes the thread pool

(2) Code implementation

What are the ways to create multi-threading in Java?
What are the ways to create multi-threading in Java?

(3) Notes
  • Create a periodic thread pool that supports scheduled and periodic execution of tasks (the first time parameter is the execution delay time, and the second parameter is the execution interval).

5) Extension of WorkStealingPool() new thread pool class ForkJoinPool
(1) Specific steps

① Create a thread pool through Executors.newWorkStealingPool()
② Rewrite the run() method of the Runnable class, call the Runnable class object through the Thread class object, and use the thread pool to perform the task
③ Sleep() allows the main thread to wait for the child thread to complete execution, or you can use a counter
④Shutdown( ) closes the thread pool

(2) Code implementation

What are the ways to create multi-threading in Java?
What are the ways to create multi-threading in Java?

(3) Notes
  • Because each thread has its own task queue, because there are more and less tasks, the CPU load may be unbalanced. This method can effectively take advantage of the advantages of multi-core CPUs. Threads with fewer tasks can "steal" tasks from threads with more tasks, thereby balancing the execution of tasks on each CPU.

The above is the detailed content of What are the ways to create multi-threading in Java?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles