Java Concurrent
2015-07-21 23:40
302 查看
Java Concurrent
ExecutorService
ExecutorService exec = Executors.newCachedThreadPool(); // create a cached pool
ExecutorService exec = Executors.newFixedThreadPool(4); // fixed sized thread pool
ExecutorService exec = Executors.newSingleThreadExecutor(); // single thread's pool
ThreadPoolExecutor
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 6, 2, TimeUnit.HOURS, queue);
3, corePoolSize
6, maximunPoolSize
2, keep alive time (idle threads will be gc after such a long time)
TimeUnit.HOURS, time units
queue,
LinkedBlockingQueue<Runnable>, or
new ArrayBlockingQueue<Runnable>(8)
当新任务在方法 execute(java.lang.Runnable) 中提交时,如果运行的线程少于 corePoolSize,则创建新线程来处理请求(即使存在空闲线程)。如果运行的线程多于 corePoolSize 而少于 maximumPoolSize,则仅当队列(queue)满时才创建新线程。如果设置的 corePoolSize 和 maximumPoolSize 相同,则创建了固定大小的线程池。如果将 maximumPoolSize 设置为基本的无界值(如 Integer.MAX_VALUE),则允许池适应任意数量的并发任务。
# AtomicInteger
AtomicInteger ac = new AtomicInteger();int index = ac.incrementAndGet();
CountDownLatch
countDown(); // decrease the count by 1
await(); // suspend the current thread until the count becomes 0
CountDownLatch c1 = new CountDownLatch(2); // like the condition in OS
Runnable VS Callable
Runnable和Callable的区别是,(1)Callable规定的方法是call(),Runnable规定的方法是run().
(2)Callable的任务执行后可返回值,而Runnable的任务是不能返回值得
(3)call方法可以抛出异常,run方法不可以
(4)运行Callable任务可以拿到一个Future对象,表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。通过Future对象可以了解任务执行情况,可取消任务的执行,还可获取执行结果。
Semaphore
Semaphore s = new Semaphore(4); // allow at most 4 threads concurrently access a piece of codes.acquire() ; // try to get the qualification to access a piece of code, wait if the current semaphore is 0
s.release(); // release the lock/semaphore
相关文章推荐
- Excel 函数语言 第一个功能实现 附带java实现
- java基础语法--02
- Java谣言终结者之Arraylist和Linkedlist到底谁快
- ibatis+springmvc的dao实现+配置文件
- eclipse打包问题:Export aborted because fatal lint errors we
- JAVA基础之多线程
- 我的第一个JavaFX程序
- java 数据库连接MySQL
- java中获取另一个线程中的信息
- Java 调用 自定义函数SQL
- JAVA 之RMI、Webservice
- Eclipse svn插件离线安装
- 如何配置java环境
- Spring分布式事务
- java学习——容器(集合)
- MyEclipse不能重新发布的解决方案
- 通过java对数据库的增删查修操作
- 15. JavaSE-包 & jar包
- eclipse启动出现“An Error has Occurred. See the log file”解决方法
- java进阶之反射:反射基础之如何获取一个类以及如何获取这个类的所有属性和方法(1)