The threads in the thread pool will process the requests on the connections concurrently.
https://docs.oracle.com/javase/tutorial/essential/concurrency/pools.html
Most of the executor implementations in java.util.concurrent
use thread pools, which consist of worker threads. This kind of thread exists separately from the Runnable
and Callable
tasks it executes and is often used to execute multiple tasks.
Using worker threads minimizes the overhead due to thread creation. Thread objects use a significant amount of memory, and in a large-scale application, allocating and deallocating many thread objects creates a significant memory management overhead.
One common type of thread pool is the fixed thread pool. This type of pool always has a specified number of threads running; if a thread is somehow terminated while it is still in use, it is automatically replaced with a new thread. Tasks are submitted to the pool via an internal queue, which holds extra tasks whenever there are more active tasks than threads.
An important advantage of the fixed thread pool is that applications using it degrade gracefully. To understand this, consider a web server application where each HTTP request is handled by a separate thread. If the application simply creates a new thread for every new HTTP request, and the system receives more requests than it can handle immediately, the application will suddenly stop responding to all requests when the overhead of all those threads exceed the capacity of the system. With a limit on the number of the threads that can be created, the application will not be servicing HTTP requests as quickly as they come in, but it will be servicing them as quickly as the system can sustain.
A simple way to create an executor that uses a fixed thread pool is to invoke the newFixedThreadPool
factory method in java.util.concurrent.Executors
This class also provides the following factory methods:
- The
newCachedThreadPool
method creates an executor with an expandable thread pool. This executor is suitable for applications that launch many short-lived tasks. - The
newSingleThreadExecutor
method creates an executor that executes a single task at a time. - Several factory methods are
ScheduledExecutorService
versions of the above executors.
If none of the executors provided by the above factory methods meet your needs, constructing instances of java.util.concurrent.ThreadPoolExecutor
orjava.util.concurrent.ScheduledThreadPoolExecutor
will give you additional options.
Java Concurrency Tutorial: Thread Pools
Thread Pools are useful when you need to limit the number of threads running in your application at the same time. There is a performance overhead associated with starting a new thread, and each thread is also allocated some memory for its stack etc.
Instead of starting a new thread for every task to execute concurrently, the task can be passed to a thread pool. As soon as the pool has any idle threads the task is assigned to one of them and executed. Internally the tasks are inserted into a Blocking Queue which the threads in the pool are dequeuing from. When a new task is inserted into the queue one of the idle threads will dequeue it successfully and execute it. The rest of the idle threads in the pool will be blocked waiting to dequeue tasks.
【多线程服务器 每个连接会在线程池中开启一个新的线程 线程池并发地处理这些请求】
Thread pools are often used in multi threaded servers. Each connection arriving at the server via the network is wrapped as a task and passed on to a thread pool. The threads in the thread pool will process the requests on the connections concurrently. A later trail will get into detail about implementing multithreaded servers in Java.
https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html
public class SimpleThreads { // Display a message, preceded by
// the name of the current thread
static void threadMessage(String message) {
String threadName =
Thread.currentThread().getName();
System.out.format("%s: %s%n",
threadName,
message);
} private static class MessageLoop
implements Runnable {
public void run() {
String importantInfo[] = {
"Mares eat oats",
"Does eat oats",
"Little lambs eat ivy",
"A kid will eat ivy too"
};
try {
for (int i = 0;
i < importantInfo.length;
i++) {
// Pause for 4 seconds
Thread.sleep(4000);
// Print a message
threadMessage(importantInfo[i]);
}
} catch (InterruptedException e) {
threadMessage("I wasn't done!");
}
}
} public static void main(String args[])
throws InterruptedException { // Delay, in milliseconds before
// we interrupt MessageLoop
// thread (default one hour).
long patience = 1000 * 60 * 60; // If command line argument
// present, gives patience
// in seconds.
if (args.length > 0) {
try {
patience = Long.parseLong(args[0]) * 1000;
} catch (NumberFormatException e) {
System.err.println("Argument must be an integer.");
System.exit(1);
}
} threadMessage("Starting MessageLoop thread");
long startTime = System.currentTimeMillis();
Thread t = new Thread(new MessageLoop());
t.start(); threadMessage("Waiting for MessageLoop thread to finish");
// loop until MessageLoop
// thread exits
while (t.isAlive()) {
threadMessage("Still waiting...");
// Wait maximum of 1 second
// for MessageLoop thread
// to finish.
t.join(1000);
if (((System.currentTimeMillis() - startTime) > patience)
&& t.isAlive()) {
threadMessage("Tired of waiting!");
t.interrupt();
// Shouldn't be long now
// -- wait indefinitely
t.join();
}
}
threadMessage("Finally!");
}
}
The threads in the thread pool will process the requests on the connections concurrently.的更多相关文章
- The CLR's Thread Pool
We were unable to locate this content in zh-cn. Here is the same content in en-us. .NET The CLR's Th ...
- Improve Scalability With New Thread Pool APIs
Pooled Threads Improve Scalability With New Thread Pool APIs Robert Saccone Portions of this article ...
- Reporting Service 告警"w WARN: Thread pool pressure. Using current thread for a work item"
如果Reporting Service偶尔出现不可访问或访问出错情况,这种情况一般没有做监控的话,很难捕捉到.出现这种问题,最好检查Reporting Service的日志文件. 今天早上就遇到这样一 ...
- DUBBO Thread pool is EXHAUSTED!
一.问题 在测试环境遇到的异常信息,如下: 16-10-17 00:00:00.033 [New I/O server worker #1-6] WARN com.alibaba.dubbo.com ...
- [Done][DUBBO] dubbo Thread pool is EXHAUSTED!
异常信息: com.alibaba.dubbo.remoting.ExecutionException: class com.alibaba.dubbo.remoting.transport.disp ...
- Running Code on a Thread Pool Thread_翻译
The previous lesson showed you how to define a class that manages thread pools and the tasks that ru ...
- MySQL Thread Pool: Problem Definition
A new thread pool plugin is now a part of the MySQL Enterprise Edition.In this blog we will cover th ...
- Thread Pool Engine, and Work-Stealing scheduling algorithm
http://pages.videotron.com/aminer/threadpool.htm http://pages.videotron.com/aminer/zip/threadpool.zi ...
- C++笔记--thread pool【转】
版权声明:转载著名出处 https://blog.csdn.net/gcola007/article/details/78750220 背景 刚粗略看完一遍c++ primer第五版,一直在找一些c+ ...
随机推荐
- ROS学习网址【原创】
ROS学习网址 http://www.ros.org/ http://www.ros.org/news/book/ http://wiki.ros.org/ http://blog.exbot.net ...
- 34深入理解C指针之---通过字符串传递函数
一.通过字符串传递函数 1.定义:可以使用函数名(字符串)调用函数,也可以使用函数指针调用函数,将两者结合 2.特征: 1).在函数声明时使用函数指针 2).调用函数时使用函数名称(字符串) 3).可 ...
- java中过滤查询文件
需求,过滤出C盘demo目录下 所有以.java的文件不区分大小写 通过实现FileFilter接口 定义过滤规则,然后将这个实现类对象传给ListFiles方法作为参数即可. 使用递归方法实现 pa ...
- 小程序 之使用HMACSHA1算法加密报文
首先说说我们前端常用的加密技术, 我们常用的加密技术有:如MD5加密,base64加密 今天要说的是HMACSHA1加密技术 先介绍下什么是SHA1算法, 安全哈希算法(Secure Hash Alg ...
- 微信小程序踩坑之一[thist]使用技巧
刚上手小程序 时,习惯把this当成jquery中的$(this)来用,实际上这两个还是有差别的 在页面方法中调用其他方法,一般是用this.function(),直接调用小程序 的方法或函数则是用w ...
- django使用logging记录日志
django使用logging记录日志,我没有用这方式去记录日志,主要还是项目小的原因吧, 有机会遇见大项目的话可以回头研究. 配置setting.py配置文件 import logging impo ...
- mac 下删除xcode后使用git
1. http://blog.bobbyallen.me/2014/03/07/how-to-install-git-without-having-to-install-xcode-on-macosx ...
- Java集合——概述
Java集合——概述 摘要:本文主要介绍了几种集合类型以及有关的一些知识点. 集合类图 类图 类图说明 所有集合类都位于java.util包下.Java的集合类主要由两个接口派生而出:Collecti ...
- Jackson对泛型的序列化和反序列化方法汇总
说明:Jackson对于简单泛型是可以正常操作的,但是如果对于太过于复杂的泛型类有时会不成功.目前还在找着更合适的Json库.不过这一点在dotnet原生方案JavaScriptSerializer可 ...
- iOS应用崩溃日志揭秘
这篇文章还可以在这里找到 英语 Learn how to make sense of crash logs! 本文作者是 Soheil Moayedi Azarpour, 他是一名独立iOS开发者. ...