CachedThreadPool

Posted jasonandy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CachedThreadPool相关的知识,希望对你有一定的参考价值。

/**
 * <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)
[email protected]4c2 creating new Thread
created Thread[Thread-0,5,main]
eh = c[email protected]6f94fa3e
run() by Thread[Thread-0,5,main]
eh = c[email protected]6f94fa3e
[email protected]4c2 creating new Thread
created Thread[Thread-1,5,main]
eh = c[email protected]3ff961b5
caught java.lang.RuntimeException in Thread[Thread-0,5,main]
*///:~

 

以上是关于CachedThreadPool的主要内容,如果未能解决你的问题,请参考以下文章

在 Java 中安排定期任务,避免在必要时创建新线程(如 CachedThreadPool)

FixedThreadPool vs CachedThreadPool:两害相权取其轻

Java并发包中的几种ExecutorService

线程池小结2

微信小程序代码片段

请问 java并发包中的 Thread exclusiveOwnerThread 为什么用 transient 修饰?