- 浏览: 58952 次
- 性别:
- 来自: 上海
文章分类
最新评论
-
java.lang.String:
好了,知道了!
垃圾收集器与内存分配策略 -
java.lang.String:
能说一下,什么是新生代,什么是老年代吗?
垃圾收集器与内存分配策略
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; 2212 // 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 } 29To 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!!
发表评论
-
Attacking memory problems on Android
2012-04-23 22:38 1408Attacking memory problems on ... -
ViewPager and Fragments
2012-03-25 20:11 2274Android: ViewPager and Fragm ... -
Image Processing in Android
2012-03-13 23:44 0While working on WallSwitch, I ... -
How to avoid OutOfMemory Error / OOM (The Ugly Truth Revealed)
2012-03-13 23:38 856ERROR/dalvikvm-heap(4204): 6 ... -
Reduce Bitmap size using BitmapFactory.Options.inSampleSize
2012-03-13 23:32 1110In the post "Load ImageVie ... -
解決在 Android 中使用 Bitmap 造成 Out of memory 的方法~
2012-03-13 23:30 1019因為Android本身的限制,在2.x版中使用 Bitm ... -
android BitmapFactory的OutOfMemoryError: bitmap size exceeds VM budget解决方案
2012-03-13 23:28 772使用android提供的BitmapFactory解码一 ... -
About Bitmap allocated
2012-03-13 23:08 1101Bitmap data is not allocated ... -
Dynamic ListView update
2012-02-19 16:39 0package com.huawei; impor ... -
SQLITE Best practice
2012-02-15 23:02 942Recently I’ve been doing qui ... -
Correct use of ConcurrentHashMap
2012-02-12 22:13 1251ConcurrentHashMap has been pitc ... -
Prof Android app dev: Creating User Interfaces
2011-12-08 19:22 0Introducing Views Android的所有可视 ... -
Prof Android app dev:Creating Applications and Activiies
2011-12-08 18:35 1657每个APP都泡在一个单独的DALVIK虚拟机实例上使用一个单独 ... -
Prof Android app dev: Introduction and Get started
2011-11-28 17:36 978对于Android来说,所有的应用程序都是平等的,第三方和原生 ... -
EffectiveJava 读书笔记2 对于所有对象都通用的方法
2011-11-21 17:37 0第8条:覆盖equals时请遵守通用约定 防止覆盖equal ... -
EffectiveJava 读书笔记1 创建和销毁对象
2011-11-20 11:50 933第1条:考虑用静态工厂 ... -
JAVA内存模型与线程
2011-11-11 17:41 0JVM规范试图定义一个JAVA ... -
运行期优化
2011-11-10 12:12 917JAVA最初是通过解释器进 ... -
编译期优化
2011-11-09 16:16 886三类编译器: 前端编译器,将JAVA编译成CLAS ... -
虚拟机字节码执行引擎
2011-11-06 11:23 2804执行引擎在执行JAVA代码的时候可以选择解释执行(通过解释器执 ...
相关推荐
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 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 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 ...
JActor 是一个 Java 的 Actor 模式的实现,经过测试在 i5 CPU 上可支持每秒钟发送超过亿条消息,可能是目前最快的。...// Shut down the thread pool. mailboxFactory.close(); 标签:JActor
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,
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 ...
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 ...
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 ...
Thread t = threadFactory.newThread(w);//使用线程工厂创建一个线程 if (t != null) { w.thread = t; workers.add(w);//保存线程池正在运行的线程 int nt = ++poolSize;//线程池的线程数加1 if (nt > ...
java concurrent源码 Java并发编程基础中的一些源码 com.ls.thread.connectionpool 一个简单的数据库连接池示例 com.ls.thread.threadpool 线程池技术示例 com.ls.repeatRequest 业务防重功能实现
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 ...
// set the sleep for the maint thread // it will wake up every x seconds and // maintain the pool size pool.setMaintSleep(30); // Tcp�Ĺ�������ڷ���һ���֮ǰ�����ػ���...
官方的说明是: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适用于批处理。当有大量的操作需要一次性...
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 ...
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 ...
另外再配置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...
A detailed walkthrough of the error, its code path and all known details is as follows: --------------------------------------------------------------------------------------- -- Head -- Stacktrace: ...
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. 翻译: 很多程序员在读完这本书,宣布自己相当...