Home > Java > javaTutorial > body text

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

PHPz
Release: 2023-04-26 16:07:19
forward
2174 people have browsed it

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!

Related labels:
source:yisu.com
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!