惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

U
Unit 42
C
Cybersecurity and Infrastructure Security Agency CISA
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Know Your Adversary
Know Your Adversary
S
Securelist
I
Intezer
AWS News Blog
AWS News Blog
L
LINUX DO - 热门话题
P
Privacy International News Feed
Recent Announcements
Recent Announcements
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
博客园 - 聂微东
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Attack and Defense Labs
Attack and Defense Labs
N
News and Events Feed by Topic
The GitHub Blog
The GitHub Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
Schneier on Security
Schneier on Security
N
Netflix TechBlog - Medium
爱范儿
爱范儿
B
Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
C
CERT Recently Published Vulnerability Notes
Hacker News: Ask HN
Hacker News: Ask HN
Google DeepMind News
Google DeepMind News
Engineering at Meta
Engineering at Meta
Blog — PlanetScale
Blog — PlanetScale
WordPress大学
WordPress大学
S
Secure Thoughts
K
Kaspersky official blog
N
News | PayPal Newsroom
O
OpenAI News
Last Week in AI
Last Week in AI
C
Check Point Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Cyberwarzone
Cyberwarzone
Application and Cybersecurity Blog
Application and Cybersecurity Blog
T
Tor Project blog
大猫的无限游戏
大猫的无限游戏
Vercel News
Vercel News
D
Docker
Hugging Face - Blog
Hugging Face - Blog
T
Threat Research - Cisco Blogs
Cisco Talos Blog
Cisco Talos Blog
The Register - Security
The Register - Security
博客园 - 司徒正美
Martin Fowler
Martin Fowler
人人都是产品经理
人人都是产品经理
P
Palo Alto Networks Blog

博客园 - cacard

Android中的内部类引起的内存泄露 Android的消息机制: Message/MessageQueue/Handler/Looper ArrayList/Vector的原理、线程安全和迭代Fail-Fast JVM中的Stack和Frame JVM中的垃圾收集算法和Heap分区简记 无锁编程以及CAS 简述Java内存模型的由来、概念及语义 MQTT协议简记 RabbitMQ的工作队列和路由 RabbitMQ 入门 [Java] LinkedHashMap 源码简要分析 [Java] HashMap 源码简要分析 [Java] Hashtable 源码简要分析 CentOS 安装 Hadoop 手记 树莓派(RespberryPi)安装手记 RPC简述 [C++] const与重载 [C++] 左值、右值、右值引用 [C++] 引用
Java线程池 / Executor / Callable / Future
cacard · 2013-07-01 · via 博客园 - cacard

为什么需要线程池?

每次都要new一个thread,开销大,性能差;不能统一管理;功能少(没有定时执行、中断等)。

使用线程池的好处是,可重用,可管理。

Executor

4种线程池

// 可缓存线程池,如果缓存中没有可用的,则移出60秒未使用过的线程

ExecutorService service= Executors.newCachedThreadPool();

// 大小固定的线程池

ExecutorService service= Executors.newFixedThreadPool(5);

// 单线程,是线程量=1的FixedThreadPool,多任务下相当于排队。

ExecutorService service= Executors.newSingleThreadPool();

// 支持定时和周期,一般情况下可替代timer

ScheduledExecutorService exec = Executors.newScheduledThreadPool(int corePoolSize)

Demo

ExecutorService pool= Executors.newCachedThredPool();

pool.ececute(new Runable());

// 关闭,不再接受新的任务请求

pool.shutdown();

// 立即关闭,停止接受task,

pool.showdownNow();

Future

.submit(Runnable) 返回一个Future,主要目的是检查任务执行的状况(是否完成,有无异常)。

interface Future<V>

{

     V get() throws ...;

     V get(long timeout,TimeUnit unit) throws ..;

     void cancel(boolean mayInterrupt); // 取消任务,如果已经开始,mayInterrupt=true时被中断

     boolean isCancelled();

     boolean isDown();

}

Future task = pool.submit(new Runnable());

task.isDone(); // 

task.get(); // 阻塞当前线程,如果task在执行过程中有异常,则会在这里重新抛出

Callable

Runnable没有返回值,Callable<E>有返回值;

submit一个runnable,不能知道运行结果,可以submit一个callable。

// 创建callable

class MyCallable implements Callable<Integer>

{

     @Override

     public Integer call()

     {

          return 1;

     }

}

Future<Integer> task = pool.submit(new MyCallable());

task.get(); // 阻塞,显示结果

FutureTask

同时包装了Future和Task。

Callable<Integer> c = ...;

FutureTask<Integer> t = new FutureTask<Integer>(c);

new Thread(task).start();

Integer r = t.get();

CompletionService

completionService = new ExecutorCompletionService<Long>(exec);

for(){

      completionService.submit(new Callable());

}

// 取完成的任务,如果没有,就阻塞等待

completionService.take().get()