Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the methods of creating multithreading by Java

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge points of this article, "what are the methods of creating multithreading in Java?", so the editor summarizes the following, detailed contents, clear steps, and a certain reference value. I hope you can get something after reading this article. Let's take a look at this "what are the ways to create multithreading in Java?"

Five methods of creating multithreading by Java (1) inheriting Thread class 1. Implementation description

By inheriting Thread and overriding its run (), the run method defines the tasks that need to be performed. The created subclass executes the thread method by calling the start () method.

By inheriting the thread class implemented by Thread, instance variables of the thread class cannot be shared among multiple threads. You need to create different Thread objects, so you naturally don't share resources.

2. Specific steps

1) define the UserThread class and inherit the Thread class

2) override the run () method

3) create UserThread object

4) call the start () method

3. Code implementation

4. Points for attention

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 sell their own tickets, there will be the problem of three ticket windows selling the same ticket.

(2) implement Runnable interface 1. Implementation description

You need to first define a class that implements the Runnable interface and override the interface's run () method, which is the thread execution body. Then create the object of the Runnable implementation class, which is the real thread object as the parameter target for creating the Thread object.

The resource sharing between threads can be realized by creating objects by using thread classes that implement the Runnable interface.

2. Specific steps

1) define a UserRun class to implement the Runnble interface

2) override the run () method

3) create an object of the UserRun class

4) create the object of the Thread class, and the object of the UserRun class is used as the parameter of the Thread class constructor.

5) start the thread

3. Code implementation

4. Points for attention

Data resource sharing, where multiple threads work together to complete a task (multiple threads share the resources that create thread objects). For example, three ticket windows (three threads) sell tickets at the same time (ticket in the MyThread class), and the three threads share resources.

(3) implement Callable interface 1. Implementation description

The Callable interface is like an upgraded version of the Runable interface, providing a call () method that acts as the executor of the thread while allowing return values.

The Callable object cannot be directly used as the target of the Thread object, because the Callable interface is a new interface of Java5, not a subinterface of the Runnable interface.

For the solution to this problem, the Future interface is introduced, which can accept the return value of call (). The RunnableFuture interface is a subinterface of the Future interface and the Runnable interface, and can be used as the target of the Thread object.

2. Specific steps

1) define the class UserCallable and implement the Callable interface

2) override the call () method

3) create an object for UserCallable

4) create an object of FutureTask, a subclass of the RunnableFuture API, and the parameter of the constructor is the object of UserCallable

5) create an object of the Thread class, and the parameter of the constructor is the object of FutureTask

6) start the thread

3. Code implementation

4. Points for attention

Data resource sharing, where multiple threads work together to complete a task (multiple threads share the resources that create thread objects). For example, three ticket windows (three threads) sell tickets at the same time (ticket in the MyThread class), and the three threads share resources. At the same time, the thread will complete the call with a return value.

(4) inheriting TimerTask class 1. Implementation description

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

Timer is a threading facility for scheduling tasks that are later executed in background threads. You can schedule a task to be executed once, or repeat it periodically, and it can be seen as a timer and TimerTask can be scheduled.

TimerTask is an abstract class that implements the Runnable interface, so it has the ability of multithreading.

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 policy of the task

3. Code implementation

4. Points for attention

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

(5) start multithreading through thread pool 1. Implementation description

Thread pools can be created through the utility class of Executors.

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

Reduce the consumption of system resources and reduce the consumption caused by thread creation and destruction by reusing existing threads.

It is convenient for the control of thread concurrency. Because if the thread is created indefinitely, it may cause excessive memory consumption and generate OOM, and it will cause the CPU to switch too much.

2. Implementation method 1) FixThreadPool (int n) fixed size thread pool (1) concrete steps

① creates a fixed size thread pool through Executors.newFixedThreadPool (5)

② overrides the run () method of the Runnable class and uses the thread pool to perform tasks

③ Shutdown () closes the thread pool

(2) Code implementation

(3) points for attention

Create a fixed size thread pool, you can achieve data resource sharing, multiple threads work together to complete a task.

2) SingleThreadExecutor () single thread pool (1) specific steps

① creates a single thread pool through Executors.newSingleThreadExecutor ()

② overrides the run () method of the Runnable class and uses the thread pool to perform tasks

③ Shutdown () closes the thread pool

(2) Code implementation

(3) points for attention

The thread pool creates only one thread to perform tasks.

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

① creates as many thread pools as possible through Executors.newCachedThreadPool ()

② overrides the run () method of the Runnable class and uses the thread pool to perform tasks

③ Shutdown () closes the thread pool

(2) Code implementation

(3) points for attention

This method creates as many threads as possible to complete the task, for example, although there are only 10 tickets in the case, the thread pool generates at least 12 threads.

4) ScheduledThreadPool (int n) timing periodic thread pool (1) specific steps

Through Executors.newScheduledThreadPool (5), ① creates a thread pool with a fixed number of core threads (the minimum number of threads maintained, which will not be recycled after thread creation), and the threads are executed on a regular basis as planned.

② overrides the run () method of the Runnable class and uses the thread pool to perform tasks

③ Shutdown () closes the thread pool

(2) Code implementation

(3) points for attention

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

5) WorkStealingPool () extension of the new thread pool class ForkJoinPool (1) concrete steps

① creates a thread pool through Executors.newWorkStealingPool ()

② overrides the run () method of the Runnable class, calls the object of the Runnable class through the object of the Thread class, and uses the thread pool to perform the task.

③ Sleep () lets the main thread wait for the child thread to finish execution, or it can use counters.

④ Shutdown () closes the thread pool

(2) Code implementation

(3) points for attention

Because each thread has its own task queue, because there are more and less tasks, it may cause CPU load imbalance. Through this method, the advantages of multi-core CPU can be effectively utilized, and threads with fewer tasks can "steal" the tasks of threads with more tasks, thus balancing the execution of each CPU task.

The above is about the content of this article on "what are the methods of creating multithreading in Java". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more related knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report