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

How to use java thread pool

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

Share

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

This article mainly introduces how to use java thread pool, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, let the editor take you to understand it.

1. Is it better to have as many threads?

Before learning multithreading, readers may have questions? If a single thread runs too slowly, can you create more than one thread to run the task? In the case of concurrency, is it better to create as many threads as possible? This is a classic question. Draw a picture to show how many threads are created, and then analyze the situation.

It takes time to create and destroy threads, and it is not cost-effective if creation time + destroy time > task execution time

The created thread needs memory to store. The created thread corresponds to a Thread object, which will occupy the heap memory of JVM. According to the jvm specification, the default maximum stack size of a thread is 1m, and this stack space also needs to be allocated from the system memory, so the more threads, the more memory is needed.

To create threads, the operating system needs to switch thread context frequently, so creating too many threads will affect performance.

Context switching (context switch): for single-core CPU, only one thread can be run at a time. For parallelism, single-core cpu can also support multi-thread execution of code. CPU is solved by allocating time slices to threads. The so-called time slices are the time allocated by CPU to each thread, and the time slices are very short, so tasks are switched after a time slice is completed. Save the state of the task before switching, so that the state of the task can be loaded the next time you switch back, so the process from saving the state of the task to loading the task is called context switching, not only between threads, but also between processes.

2. How to use multithreading correctly?

What if it's a computational task?

1 to 2 times the number of CPU

But what if it's an IO-intensive task?

More threads are needed, which should be considered and decided according to the specific io blocking time.

3. The working principle of Java thread pool

Receive tasks and put them into the task repository of the thread pool

The worker thread is fetched from the task repository of the thread pool and executed

When there is no task, the thread blocks and wakes up the thread when there is a task.

4. Master API of JUC thread pool

Executor: interface class

ExecutorService: add shutdown method and support for Runnable, Callable, Future

Shutdown: those submitted will be executed.

ShutdownNow: the execution in progress will be completed, and the return of future execution

AwaitTermination: blocking waiting for the task to be closed to complete

Submit type: all submit tasks, supporting Runnable and Callable

Of type invokeAll: performs all tasks in the collection

ScheduleExecutorService: add support for scheduled tasks

Where schedule (Runablle, long, Timeunit) and schedule (Callable, long, TimeUnit) indicate how long it will be executed, while the scheduleAtFixedRate method and scheduleWithFixedDelay method both indicate periodic repetition.

Describe the difference between the scheduleAtFixedRate method and the scheduleWithFixedDelay method:

ScheduleAtFixedRate: repeat tasks at a fixed time frequency, such as every 10 seconds, that is, two tasks are executed directly at fixed intervals, regardless of whether the task is completed or not

ScheduleWithFixedDelay: repeat a task with a fixed delay, no matter how long the task takes, and then execute the next task at predetermined intervals such as 3s, with the same interval between each task

Executors: a utility class for quickly getting thread pools, and a factory class for creating thread pools

NewFixedThreadPool (int nThreads): create a thread pool of fixed size and unbounded task queues. Number of core threads in the thread pool = maximum thread pool = nThreads

NewCachedThreadPool (): creates an unbounded pool of buffered threads. Its task queue is a synchronization queue. If there are idle threads in the queue, execute with idle threads, and if not, create a new thread to execute. If the thread in the pool is idle for more than 60 seconds, it will be released. Buffer thread pools are used to perform less time-consuming asynchronous tasks. Number of core threads in thread pool = 0, maximum thread pool = Integer.MAX_VALUE

NewSingleThreadExecutor (): creates a single thread pool with only one thread to execute an unbounded task queue. The thread pool executes one joined task sequentially, with only one thread executing at any one time. The difference between a single thread pool and newFixedThreadPool (1) is that the pool size of a single thread pool cannot be changed.

NewScheduleThreadPool (int corePoolSize): a pool of threads that can execute tasks regularly. The number of core threads in this pool is specified by the parameter corePoolSize, and the maximum number of threads = Integer.MAX_VALUE

NewWorkStealingPool (): work-stealing thread pool (ForkJoinPool) created with the number of processors available on the current system as the parallel level

NewWorkStealingPool (int parallelism): work-stealing thread pool (ForkJoinPool) created at the specified parallelism parallel level

ThreadPoolExecutor: standard implementation of thread pool

The main parameters of ThreadPoolExecutor are listed below:

Parameter describes the number of corePoolSize core threads maxPoolSize maximum number of threads keepAliveTime+ time unit ThreadFactory thread factory for idle threads, which is used to create a queue for threads workQueue to store tasks, which can be called work queue Handler to handle rejected tasks

Although Executors is easy to use, it is emphasized in the Ali programming specification to be cautious in creating thread pools with Executors. The following is an excerpt from the Ali programming specification manual:

[mandatory] Thread pools are not allowed to be created using Executors, but through ThreadPoolExecutor

This way of processing makes the students more clear about the running rules of the thread pool and avoid the risk of resource exhaustion.

Description: the disadvantages of each method of Executors:

1) newFixedThreadPool and newSingleThreadExecutor:

The main problem with    is that stacked request processing queues can consume a lot of memory, even OOM.

2) newCachedThreadPool and newScheduledThreadPool:

The main problem with    is that the maximum number of threads is Integer.MAX_VALUE, which may create a very large number of threads, or even OOM.

Basic parameters of ThreadPoolExecutor:

New ThreadPoolExecutor (2, / / the number of core threads is 5, / / the maximum number of threads is 60L, / / keepAliveTime. If the thread is idle beyond this number, it will be destroyed to release TimeUnit.SECONDS, / / the time unit of keepAliveTime new ArrayBlockingQueue (5)) / / input the work queue with a boundary of 5

The flowchart shows that the core parameters of the thread pool are corePoolSize, maxPoolSize, workQueue (work queue).

Schematic diagram of how the thread pool works: tasks can be kept until the thread pool is full, and then other threads will be reasonably recycled except for the core thread. So normally, the number of threads in the thread pool will be within the closed range of corePoolSize and maximumPoolSize.

Basic example of ThreadPoolExecutor:

ExecutorService service = new ThreadPoolExecutor (2,5,60L, TimeUnit.SECONDS, new ArrayBlockingQueue (5)); service.execute (()-> {System.out.println (String.format ("thread name:%s", Thread.currentThread (). GetName ());}); / / avoid memory leaks, remember to close thread pool service.shutdown ()

Examples of ThreadPoolExecutor plus Callable and Future:

Public static void main (String [] args) {ExecutorService service = new ThreadPoolExecutor (2,5,60L, TimeUnit.SECONDS, new ArrayBlockingQueue (5)); Future future = service.submit (new CallableTask ()); Thread.sleep (3000); System.out.println ("future is done?" + future.isDone ()) If (future.isDone ()) {System.out.println ("callableTask return parameter:" + future.get ());} service.shutdown ();} static class CallableTask implements Callable {@ Override public Integer call () {return ThreadLocalRandom.current () .ints (0, (99 + 1)) .limit (1) .findFirst () .getAsInt () }} Thank you for reading this article carefully. I hope the article "how to use java thread pool" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

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