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 Runnableand 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
newCachedThreadPoolmethod creates an executor with an expandable thread pool. This executor is suitable for applications that launch many short-lived tasks. - The
newSingleThreadExecutormethod creates an executor that executes a single task at a time. - Several factory methods are
ScheduledExecutorServiceversions 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+ ...
随机推荐
- 三读bootmem【转】
转自:http://blog.csdn.net/lights_joy/article/details/2704788 版权声明:本文为博主原创文章,未经博主允许不得转载. 目录(?)[-] 11 ...
- Scrapy学习-19-远程管理telnet功能
使用scrapy的telnet功能远程管理scrapy运行 用法 telnet <IP_ADDR> <PORT> 官方文档 https://doc.scrapy.org/en/ ...
- jQuery实现tab选项卡效果小demo
html页面: <section> <h2>Section Title</h2> <ul class="tab-nav"> < ...
- stun简介
转载 http://blog.csdn.net/mazidao2008/article/details/4934257 STUN(Simple Traversal of UDP over NATs,N ...
- mybatis 源码学习(一)配置文件初始化
mybatis是项目中常用到的持久层框架,今天我们学习下mybatis,随便找一个例子可以看到通过读取配置文件建立SqlSessionFactory,然后在build拿到关键的sqlsession,这 ...
- mysql存储过程命令行批量插入N条数据命令
原文:http://blog.csdn.net/tomcat_2014/article/details/53377924 delimiter $$ create procedure myproc () ...
- java IOUtils下载图片
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.Inp ...
- 全面解读java虚拟机(面试考点大全)d
学习java以来,jvm的原理已经看过好多遍了,可是很多知识点都串不起来. 今天我把jvm相关知识整理了一下,看完之后肯定会对JVM很的清楚. JVM是虚拟机,也是一种规范,他遵循着冯·诺依曼体系结构 ...
- 如何突破Windows环境限制打开“命令提示符”
如今,许多企业或组织都会通过使用受限的windows环境来减少系统表面的漏洞.系统加固的越好,那么也就意味着能被访问和使用到的功能就越少. 我最近遇到的情况是,一个已经加固的系统同时受到McAfee ...
- String空格删除和java删除字符串最后一个字符的几种方法
1. String.trim()trim()是去掉首尾空格2.str.replace(" ", ""); 去掉所有空格,包括首尾.中间复制代码 代码如下:Str ...