/**
* <html>
* <body>
* <P> Copyright 1994 JsonInternational</p>
* <p> All rights reserved. - https://github.com/Jasonandy/Java-Core-Advanced </p>
* <p> Created by Jason</p>
* </body>
* </html>
*/
package cn.ucaner.core.concurrent; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; /**
* @Package:cn.ucaner.core.concurrent
* @ClassName:CachedThreadPool
* @Description: <p>
* https://blog.csdn.net/agoodcoolman/article/details/44082181
* https://www.zhihu.com/question/23212914
* 创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程
*
* 线程池为无限大,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程。
* Star : https://www.cnblogs.com/baizhanshi/p/5469948.html</p>
* @Author: - Jason
* @CreatTime:2018年5月16日 下午6:04:59
* @Modify By:
* @ModifyTime: 2018年5月16日
* @Modify marker:
* @version V1.0
*/
public class CachedThreadPool { public static void main(String[] args) { ExecutorService exec = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
exec.execute(new LiftOff());
}
exec.shutdown();
}
}
/**
* <html>
* <body>
* <P> Copyright 1994 JsonInternational</p>
* <p> All rights reserved. - https://github.com/Jasonandy/Java-Core-Advanced </p>
* <p> Created by Jason</p>
* </body>
* </html>
*/
package cn.ucaner.core.concurrent; import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future; /**
* @Package:cn.ucaner.core.concurrent
* @ClassName:CallableDemo
* @Description: <p> CallableDemo </p>
* @Author: -
* @CreatTime:2018年6月12日 下午3:50:49
* @Modify By:
* @ModifyTime: 2018年6月12日
* @Modify marker:
* @version V1.0
*/
public class CallableDemo { public static void main(String[] args) { ExecutorService exec = Executors.newCachedThreadPool(); ArrayList<Future<String>> results = new ArrayList<>(); for (int i = 0; i < 10; i++) {
results.add(exec.submit(new TaskWithResult(i)));
} for (Future<String> fs : results) {
try {
System.out.println(fs.get());
} catch (InterruptedException e) {
System.out.println(e);
e.printStackTrace();
} catch (ExecutionException e) {
System.out.println(e);
e.printStackTrace();
} finally {
exec.shutdown();
}
}
}
} class TaskWithResult implements Callable<String> {
private int id; public TaskWithResult(int id) {
this.id = id;
} @Override
public String call() throws Exception {
return "result of TaskWithResult " + id;
}
}
//Outputs
//result of TaskWithResult 0
//result of TaskWithResult 1
//result of TaskWithResult 2
//result of TaskWithResult 3
//result of TaskWithResult 4
//result of TaskWithResult 5
//result of TaskWithResult 6
//result of TaskWithResult 7
//result of TaskWithResult 8
//result of TaskWithResult 9
/**
* <html>
* <body>
* <P> Copyright 1994 JsonInternational</p>
* <p> All rights reserved. - https://github.com/Jasonandy/Java-Core-Advanced </p>
* <p> Created by Jason</p>
* </body>
* </html>
*/
package cn.ucaner.core.concurrent; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory; /**
* @Package:cn.ucaner.core.concurrent
* @ClassName:CaptureUncaughtException
* @Description: <p> 捕捉异常</p>
* @Author: - Jason
* @CreatTime:2018年5月16日 下午6:10:37
* @Modify By:
* @ModifyTime: 2018年5月16日
* @Modify marker:
* @version V1.0
*/
public class CaptureUncaughtException { public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool(
new HandlerThreadFactory());
exec.execute(new ExceptionThread());
}
} class ExceptionThread implements Runnable {
public void run() {
Thread t = Thread.currentThread();
System.out.println("run() by " + t);
System.out.println(
"eh = " + t.getUncaughtExceptionHandler());
throw new RuntimeException();
}
} class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
System.out.println("caught " + e + " in " + t);
}
} class HandlerThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
System.out.println(this + " creating new Thread");
Thread t = new Thread(r);
System.out.println("created " + t);
t.setUncaughtExceptionHandler(
new MyUncaughtExceptionHandler());
System.out.println(
"eh = " + t.getUncaughtExceptionHandler());
return t;
}
} /* Output: (90% match)
com.brianway.learning.java.concurrent.HandlerThreadFactory@266474c2 creating new Thread
created Thread[Thread-0,5,main]
eh = com.brianway.learning.java.concurrent.MyUncaughtExceptionHandler@6f94fa3e
run() by Thread[Thread-0,5,main]
eh = com.brianway.learning.java.concurrent.MyUncaughtExceptionHandler@6f94fa3e
com.brianway.learning.java.concurrent.HandlerThreadFactory@266474c2 creating new Thread
created Thread[Thread-1,5,main]
eh = com.brianway.learning.java.concurrent.MyUncaughtExceptionHandler@3ff961b5
caught java.lang.RuntimeException in Thread[Thread-0,5,main]
*///:~

CachedThreadPool的更多相关文章

  1. [Java并发编程(二)] 线程池 FixedThreadPool、CachedThreadPool、ForkJoinPool?为后台任务选择合适的 Java executors

    [Java并发编程(二)] 线程池 FixedThreadPool.CachedThreadPool.ForkJoinPool?为后台任务选择合适的 Java executors ... 摘要 Jav ...

  2. [Java并发编程(一)] 线程池 FixedThreadPool vs CachedThreadPool ...

    [Java并发编程(一)] 线程池 FixedThreadPool vs CachedThreadPool ... 摘要 介绍 Java 并发包里的几个主要 ExecutorService . 正文 ...

  3. CachedThreadPool里的线程是如何被回收的?

    线程池创建线程的逻辑图: 我们分析CachedThreadPool线程池里的线程是如何被回收的. //Executors public static ExecutorService newCached ...

  4. 线程池CachedThreadPool

    没有核心线程,只有非核心线程,并且每个非核心线程空闲等待的时间为60s,采用SynchronousQueue队列 由于maximumPoolSize是无界的,所以如果线程处理任务速度小于提交任务的速度 ...

  5. cachedThreadPool缓存线程池

    package com.loan.modules.common.util; import java.util.concurrent.BlockingQueue; import java.util.co ...

  6. java 线程池——异步任务

    一.简单粗暴的线程 最原始的方式,当我们要并行的或者异步的执行一个任务的时候,我们会直接使用启动一个线程的方式,如下面所示: new Thread(new Runnable() { @Override ...

  7. java之并发编程线程池的学习

    如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了,这样频繁创建线程就会大大降低系统的效率,因为频繁创建线程和销毁线程需要时间. java.uitl.concurrent.Thre ...

  8. ExecutorService线程池

    ExecutorService 建立多线程的步骤: 1.定义线程类 class Handler implements Runnable{} 2.建立ExecutorService线程池 Executo ...

  9. javase-->多线程--线程池

    java的线程池理解 在面向对象编程中,对象创建和销毁是很费时间的,因为创建一个对象要获取内存资源或者其它更多资源.在Java中更是如此,虚拟机将试图跟踪每一个对象,以便能够在对象销毁后进行垃圾回收. ...

随机推荐

  1. 海底高铁(洛谷 P3406)

    题目背景 大东亚海底隧道连接着厦门.新北.博艾.那霸.鹿儿岛等城市,横穿东海,耗资1000亿博艾元,历时15年,于公元2058年建成.凭借该隧道,从厦门可以乘坐火车直达台湾.博艾和日本,全程只需要4个 ...

  2. Spark2.x(五十六):Queue's AM resource limit exceeded.

    背景: 按照业务需求将数据拆分为60份,启动60个application分别运行对每一份数据,application的提交脚本如下: #/bin/sh #LANG=zh_CN.utf8 #export ...

  3. delete、truncate、drop三种删除语句联系与区别

    相同点: 1.truncate和不带where子句的delete.以及drop都会删除表内的数据. 2.drop.truncate都是DDL语句(数据定义语言),执行后会自动提交. 不同点: 1. t ...

  4. java8之Spliterator

    基本用法: import java.util.Arrays; import java.util.Spliterator; import java.util.stream.IntStream; publ ...

  5. Mac 上ssh远程连接Linux服务器提示Host key verification failed.

    当我们对重装远程服务器的时候会出现Host key verification failed问题 解决办法: rm -rf ~/.ssh/known_hosts 重新ssh连接,OK!

  6. pm2 工具来管理 node 服务端

    如下: nodeServer.js 'use strict'; const http = require('http'); const server = http.createServer(funct ...

  7. (转)matplotlib实战

    原文:https://www.cnblogs.com/ws0751/p/8361330.html https://www.cnblogs.com/ws0751/p/8313017.html---mat ...

  8. 时间工具类DateUtil

    import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; impor ...

  9. 使用C++调用并部署pytorch模型

    1.背景(Background) 上图显示了目前深度学习模型在生产环境中的方法,本文仅探讨如何部署pytorch模型! 至于为什么要用C++调用pytorch模型,其目的在于:使用C++及多线程可以加 ...

  10. [LeetCode] 774. Minimize Max Distance to Gas Station 最小化加油站间的最大距离

    On a horizontal number line, we have gas stations at positions stations[0], stations[1], ..., statio ...