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 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.的更多相关文章

  1. 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 ...

  2. Improve Scalability With New Thread Pool APIs

    Pooled Threads Improve Scalability With New Thread Pool APIs Robert Saccone Portions of this article ...

  3. Reporting Service 告警"w WARN: Thread pool pressure. Using current thread for a work item"

    如果Reporting Service偶尔出现不可访问或访问出错情况,这种情况一般没有做监控的话,很难捕捉到.出现这种问题,最好检查Reporting Service的日志文件. 今天早上就遇到这样一 ...

  4. DUBBO Thread pool is EXHAUSTED!

    一.问题 在测试环境遇到的异常信息,如下: 16-10-17 00:00:00.033 [New I/O server worker #1-6] WARN  com.alibaba.dubbo.com ...

  5. [Done][DUBBO] dubbo Thread pool is EXHAUSTED!

    异常信息: com.alibaba.dubbo.remoting.ExecutionException: class com.alibaba.dubbo.remoting.transport.disp ...

  6. 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 ...

  7. 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 ...

  8. Thread Pool Engine, and Work-Stealing scheduling algorithm

    http://pages.videotron.com/aminer/threadpool.htm http://pages.videotron.com/aminer/zip/threadpool.zi ...

  9. C++笔记--thread pool【转】

    版权声明:转载著名出处 https://blog.csdn.net/gcola007/article/details/78750220 背景 刚粗略看完一遍c++ primer第五版,一直在找一些c+ ...

随机推荐

  1. struts中json机制与普通页面跳转机制混用(全局结果集配置返回json)

    package继承json-default与struts-default 返回结果是add的话将addResult属性转换为json返回(addResult属性有getter,setter方法),返回 ...

  2. hdu 5976 Detachment 脑洞题 猜结论

    题目链接 题意 将\(x\)拆成\(a_1+a_2+...+\)的形式,且\(a_1\lt a_2\lt...\),使得\(a_1*a_2*...\)取到最大值 思路 大胆猜结论. 首先拆分的形式中肯 ...

  3. select与stdio混合使用的不良后果

    参考以下链接自己补充实验:http://www.cppblog.com/mysileng/archive/2013/01/15/197284.aspx?opt=admin int main(int a ...

  4. dpkg --add-architecture i386 && apt-get update && > apt-get install wine32

    dpkg --add-architecture i386 && apt-get update &&> apt-get install wine32

  5. Netty中NioEventLoopGroup的创建源码分析

    NioEventLoopGroup的无参构造: public NioEventLoopGroup() { this(0); } 调用了单参的构造: public NioEventLoopGroup(i ...

  6. 随笔:Golang 时间Time

    先了解下time类型: type Time struct { // sec gives the number of seconds elapsed since // January 1, year 1 ...

  7. DELPHI跨平台编译开关

    DELPHI跨平台编译开关 DELPHI 现在是跨平台的开发工具,已经不仅仅针对WINDOWS OS. 跨平台的时候,一些WINDOWS特有的API或语法是不能用的,必须使用跨平台的新语法,要用编译开 ...

  8. 邁向IT專家成功之路的三十則鐵律 鐵律二十二:IT人升遷之道-無為

    升遷管道是許多人求職時相當重要的考量之一,畢竟人除了很愛錢之外更愛顯赫的頭銜,然而在企業中越顯赫的頭銜,其背後通常有更多的罵名,因為許多人的高官厚爵都是踩著一群人的頭頂爬上去的,隨時哪一天跌了下來,都 ...

  9. 精简版的MySQL制作步骤

    1.删除所有的目录,只保留 datasharebin 2.删除BIN下面除以下三个文件之外的所有文件: libmysql.dll(MYSQL5中的文件,在MYSQL5.5中不存在)mysqladmin ...

  10. linux删除空行操作:awk、grep、tr、sed

    如下:如何删除空行 shen\nshen\\n sen seh sehe she she 真正删除空行,可以使用vim: 通过命令模式删除空行.vim在命令模式下(在vim里输入英文字符:进入命令模式 ...