In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "there are several thread pools in Java". The explanation in the article is simple and clear, easy to learn and understand. Please follow the editor's train of thought to study and learn "there are several thread pools in Java".
Thread pool, as the name implies, the pool of threads, how many threads this pool can hold depends on what kind of thread pool you use, your hardware resources, and the number of concurrent threads. JDK provides the following four thread pools:
The simplest thread pool with a fixed number of threads
Creating a thread pool in Java is simple and requires only two lines of code.
ExecutorService executor = Executor.newFixedTreadPool (6); / / the fixed thread is a multiple of the number of processor cores that the thread is generally set to, because my machine is 6 cores, so it is set to 6. This is also making full use of the hardware.
/ / execute thread task executor.execute (new Runnable () {@ Overridepublic void run () {/ / do nothing}}) executor.shutdown ()
Executor is provided in the Java concurrent package to create different types of thread pools.
Attention
However, in multi-person cooperation or some deployment online projects, it is not allowed to use this method, because it has performance risks.
When Executors creates a thread pool, it uses new LinkedBlockingQueue (), which itself is unbounded, but has a fixed number of threads. This means that a maximum of N threads will be active while the program is running. Every time a new task comes, it waits until a thread is idle. All threads will be in the thread pool until shutdown () is executed.
Its problem is that it is open to all, as long as there is a task to come, you wait in the queue. In the queue and out of the queue is not the same lock, on multi-processor machines, it is possible to achieve a real sense of parallelism. Take the classic producers and consumers as an example, some are consuming and some are producing at the same time.
This thread pool does not destroy threads, reject tasks, and fix the number of threads. So if you keep adding tasks, it will lead to a very bad memory footprint, and the old age may be full.
Slightly more complex (you can defer execution or perform tasks with return values)
Public static void main (String [] args) throws InterruptedException, ExecutionException {TestThread testThread = new TestThread (); System.out.println (testThread.processors)
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool (6); FutureTask futureTask = new FutureTask (new Callable () {@ Override public String call () throws Exception {return Thread.currentThread () .getName ();}}); scheduledExecutorService.submit (futureTask)
/ / get the return value String result = futureTask.get (); System.out.println ("result:" + result)
/ / execute deferred task scheduledExecutorService.schedule (new Runnable () {@ Override public void run () {System.out.println (Thread.currentThread (). GetName () + ": bomb!");}, 3L TimeUnit. Seconds);}
Output:
Result: pool-1-thread-1
Pool-1-thread-1: bomb!
Cached thread pool
The core pool size is 0, and the maximum number of threads in the thread pool is the maximum integer, which means that all tasks will be wait as soon as they are submitted. When a thread in the thread pool does not perform a task for 60 seconds, it is Kill, and the blocking queue is listed as SynchronousQueue. The take operation of SynchronousQueue requires the put operation to wait, and the put operation requires the take operation to wait, otherwise it will block (the blocking queue of the thread pool cannot be stored, so when the current thread is busy, it will open up a new thread to process the request * *), and the thread will enter the wait set.
To sum up, this is a thread pool that can be expanded infinitely; it is suitable for tasks with relatively small execution time; threads that are idle for more than 60s will be Kill, so when they are idle for a long time, this thread pool takes up almost no resources, because there are no threads in it at all. The blocking queue has no storage space, and as soon as the request arrives, you must find an idle thread to process the request, or open a new thread in the thread pool if it is not found.
If the main thread commits tasks much faster than CachedThreadPool, CachedThreadPool will continue to create new threads to execute tasks, which may cause the system to run out of CPU and memory resources, so pay attention to controlling the number of concurrent tasks when using this thread pool. If it is a growing task demand, it will easily lead to performance bottlenecks, which will keep creating new threads.
ExecutorService cachedThreadPool = Executors.newCachedThreadPool (); for (int I = 0; I < 10; iTunes +) {cachedThreadPool.execute (new Runnable () {@ Override public void run () {System.out.println (Thread.currentThread (). GetName ());}});} cachedThreadPool.shutdown ()
Output:
Pool-1-thread-2
Pool-1-thread-6
Pool-1-thread-1
Pool-1-thread-7
Pool-1-thread-8
Pool-1-thread-3
Pool-1-thread-5
Pool-1-thread-9
Pool-1-thread-4
Pool-1-thread-10
Thread pool for a single thread
A SingleThreadExecutor is an Executor that uses a single worker thread. There is only one situation in which a new thread will join the thread pool, that is, an exception is thrown when the original thread is running, and a new thread is created to replace its work.
In the case of the producer-consumer model, this is a single-consumer model.
(ps. Generally, it can be used to do some logging.
Public static void main (String [] args) {/ / is always a thread ExecutorService singleThreadPool = Executors.newSingleThreadExecutor (); for (int I = 0; I < 10; iTunes +) {final int j = I SingleThreadPool.execute (new Runnable () {@ Override public void run () {System.out.println (Thread.currentThread (). GetName () + ": + j);}});} singleThreadPool.shutdown ();}
Output:
Pool-1-thread-1:0
Pool-1-thread-1:1
Pool-1-thread-1:2
Pool-1-thread-1:3
Pool-1-thread-1:4
Pool-1-thread-1:5
Pool-1-thread-1:6
Pool-1-thread-1:7
Pool-1-thread-1:8
Pool-1-thread-1:9
Thank you for reading, the above is the content of "there are several thread pools in Java". After the study of this article, I believe you have a deeper understanding of the problem of several thread pools in Java, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.