`
raging_sweet
  • 浏览: 58952 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

The Java Thread Pool

 
阅读更多

A thread pool helps to constrain the number of threads that may be running in an application at any one time. As threads require system resources, having too many threads executing simultaneously will negatively impact on a system’s performance.

Threads can be represented as objects. To define what our threads will be doing, we create a class that implements the Callable interface. In this example, the thread will computer an integer. The interface, itself, provides only one method – call. This is the method that is actually executed when the thread is running. Since we have assigned the integer as the generic type in the class definition, the method must also return an integer (see thegenerics guide for information on generics).

import java.util.concurrent.Callable;
 2    
 3    public class ExecAdd implements Callable<Integer>
 4    {
 5      private int id = 0;
 6      
 7      public ExecAdd (int threadId) 
 8      {
 9          id = threadId;
10      }
11    
12      /**
13       * This is the method that will be executed
14       * when the thread is running.
15       */
16      @Override
17      public Integer call() throws Exception
18      {
19          int result = 1;
20          System.out.println("Thread " + id +
21                  " calculating …");
22          
23          // Compute the result.
24          for (int value = 1; value <= id; value++)
25          {
26              result = result + value;
27          }
28          
29          // Delay for a visible amount of time. 
30          // This is just for show. 
31          try {
32              Thread.sleep(2000);
33          } catch (InterruptedException e) {
34              System.out.println("Interrupted");
35          }
36    
37          return result;
38      }
39    }

 Note that the call to sleep at line 32 is only intended to make the thread last a bit longer. It will, later, cause the thread pool to fill up and force other threads to wait before executing. The creation of the thread pool in which to execute these threads and the extraction of the return values from them is done in the main method of another class.

import java.util.ArrayList;
 3    import java.util.List;
 4    import java.util.concurrent.ExecutionException;
 5    import java.util.concurrent.ExecutorService;
 6    import java.util.concurrent.Executors;
 7    import java.util.concurrent.Future;
 8    
 9    public class ThreadCreator {
10      public static void main(String[] args) {

 The thread pool Executors class provides several methods for creating different types of thread pools. For this example, the fixed thread pool is used. A fixed thread pool will allow up to a certain number of threads to run at any one time. To show this behaviour, the example uses a thread pool size of ten but will later give thirty threads to the pool to execute.

 // Use a thread pool executor to generate 20          // Reference to the results.
21          List<Future<Integer>> allResults = null;
22   
  12 // the lists. 13 ExecutorService calcExecutor = 14 Executors.newFixedThreadPool(10); 15 16 // Maintains a reference to our adders. 17 ArrayList<ExecAdd> adders = new 18 ArrayList<ExecAdd>(); 19

 The use of a list to maintain references to the threads is so that the threads will be started simultaneously (the execution of the threads comes later). When the thread pool finishes executing a thread, the return value from the thread execution is obtained through the Future object.

20          // Reference to the results.
21          List<Future<Integer>> allResults = null;
22   

 Next, we create the instances of the thirty threads that will be executed in the thread pool.

23          // Create an instance of the calculators
24          // to be executed.
25          for (int index = 0; index < 30; index++) 
26          {
27              adders.add(new ExecAdd(index));
28          }
29   
 To execute the threads, the list of the threads are given to the thread pool.

30          try {
31              // Perform the calculations.
32              allResults = calcExecutor.
33                  invokeAll(adders);
34              
35              // Output the results.
36              for (Future<Integer> calcResult:
37                  allResults) 
38              {
39                  System.out.println(
40                          calcResult.get());
41              }
42    

 When the get() method is called, the system will wait for the thread to finish execution if it has not finished already and then return the result. All that is left is the handling of the exceptions that can possibly be thrown.'

43          } catch (InterruptedException e) {
44              System.out.println("Interrupted");
45          } catch (ExecutionException e) {
46              System.out.println(
47                      "Execution exception");
48          }
49          
50      }
51    }
 When you execute the code, you should notice a slight pause in between a batch of threads. This is because we have a thread pool of ten that executes at any one time, but we gave it thirty threads!!
分享到:
评论

相关推荐

    深入java虚拟机(inside the java virtual machine)

    Inside the Java Virtual Machine Bill Venners $39.95 0-07-913248-0 Inside the Java Virtual Machine Acknowledgments Introduction Part One: Java's Architecture 1 Introduction to Java's Architecture Why ...

    Java concurrency in practice

    Java 5.0 is a huge step forward for the development of concurrent applications in Java, providing new higherͲlevel components and additional lowͲlevel mechanisms that make it easier for novices and ...

    Reactive Streams in Java: Concurrency with RxJava, Reactor, and Akka Streams

    Reactive Streams in Java explains how to manage the exchange of stream data across an asynchronous boundary―passing elements on to another thread or thread-pool―while ensuring that the receiving ...

    Actor模式的Java实现JActor.zip

    JActor 是一个 Java 的 Actor 模式的实现,经过测试在 i5 CPU 上可支持每秒钟发送超过亿条消息,可能是目前最快的。...// Shut down the thread pool. mailboxFactory.close();   标签:JActor

    JBoss 性能调优

    JBoss AS 5 Performance Tuning will teach you how to deliver fast applications on the JBoss Application Server and Apache Tomcat, giving you a decisive ... Learn about thread pool tuning, EJB tuning,

    JBoss AS 5 Performance Tuning.pdf

    Learn about thread pool tuning, EJB tuning, and JMS tuning, which are crucial parts of enterprise applications. The persistence layer and the JBoss Clustering service are two of the most crucial ...

    Oracle WebLogic Server 10gR3: Troubleshooting Methodologies

    Basic knowledge of the Java programming language Working knowledge of the Java Virtual Machine Working knowledge with Linux Operating System Course Objectives List the uses of software patterns ...

    java面试宝典

    189、Can a Java Thread be started from Servlet class, and what will be the implications? 45 190、What is HTTP Session tracking and why is it important? 45 191、What is session management, and how is ...

    java线程池概念.txt

    Thread t = threadFactory.newThread(w);//使用线程工厂创建一个线程 if (t != null) { w.thread = t; workers.add(w);//保存线程池正在运行的线程 int nt = ++poolSize;//线程池的线程数加1 if (nt &gt; ...

    javaconcurrent源码-The-Art-of-Concurrency-Programming:TheArtofJavaConcurr

    java concurrent源码 Java并发编程基础中的一些源码 com.ls.thread.connectionpool 一个简单的数据库连接池示例 com.ls.thread.threadpool 线程池技术示例 com.ls.repeatRequest 业务防重功能实现

    Apache Geronimo 2.1_ Quick Reference.pdf

    Table of Contents Preface 1 Chapter 1: Getting Started with Geronimo 7 Motivation behind the Geronimo project 7 ...Using the Java Logging API 333 Using the SLF4j logging adapter ...

    MCCUtil 工具的使用

    // set the sleep for the maint thread // it will wake up every x seconds and // maintain the pool size pool.setMaintSleep(30); // Tcp�Ĺ�������ڷ���һ���֮ǰ�����ػ���...

    jedis使用指南

    官方的说明是:starts a pipeline,which is a very efficient way to send lots of command and read all the responses when you finish sending them。简单点说pipeline适用于批处理。当有大量的操作需要一次性...

    ordered-scheduler:解锁有序列排序要求的代码

    thread pool) public void execute() { FooInput input; synchronized ( this ) { // this call needs to be synchronized along the write() to guarantee same ordering input = read(); // this call is ...

    python3.6.5参考手册 chm

    Python参考手册,官方正式版参考手册,chm版。以下摘取部分内容:Navigation index modules | next | Python » 3.6.5 Documentation » Python Documentation contents What’s New in Python ...PEP 343: The ‘with...

    千方百计笔试题大全

    189、Can a Java Thread be started from Servlet class, and what will be the implications? 45 190、What is HTTP Session tracking and why is it important? 45 191、What is session management, and how is ...

    ELK6.2.4搭建

    另外再配置ES的时候,threadpool.bulk.queue_size 已经变成了thread_pool.bulk.queue_size ,ES_HEAP_SIZE,ES_MAX_MEM等配置都变为ES_JAVA_OPTS这一配置项,如限制内存最大最小为1G: 1 export ES_JAVA_OPTS="-Xms1...

    SogouExplorer.exe

    A detailed walkthrough of the error, its code path and all known details is as follows: --------------------------------------------------------------------------------------- -- Head -- Stacktrace: ...

    二十三种设计模式【PDF版】

    If you've never read the Design Patterns book then you have suffered a very serious gap in your programming education that should be remedied immediately. 翻译: 很多程序员在读完这本书,宣布自己相当...

Global site tag (gtag.js) - Google Analytics