如果线程池中线程任务已经执行完毕了,当前线程的状态是怎样的?

1.代码样例

int corePoolSize = 2;
    int maximumPoolSize = 4;
    long keepAliveTime = 20;
    TimeUnit unit = TimeUnit.SECONDS;
    ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
        keepAliveTime, unit, new ArrayBlockingQueue<>(10), new NameTreadFactory(),
        new ThreadPoolExecutor.CallerRunsPolicy());
//    executor.allowCoreThreadTimeOut(true);
 // 如果设置此值,线程执行完毕,会等keepAliveTime时长,如果还没有任务执行,线程池中线程就关闭了
    executor.prestartAllCoreThreads(); // 预启动所有核心线程
    try {
      Thread.sleep(10 * 1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("开始任务-------------------");
    for (int i = 0; i < 20; i++) {
      Task task = new Task(i);
      executor.execute(task);
    }
    System.out.println("结束任务--------------------------");

    try {
      Thread.sleep(300 * 1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    executor.shutdown();


public class NameTreadFactory implements ThreadFactory {

    private final AtomicInteger mThreadNum = new AtomicInteger(1);

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(r, "my-thread-" + mThreadNum.getAndIncrement());
        System.out.println(t.getName() + " has been created");
        return t;
    }
}

 

2.如使用默认的线程池,任务执行完毕,线程池中会保持核心线程池的个数(2个)处于等待状态 waiting。

 

 

 

3.如果设置了

executor.allowCoreThreadTimeOut(true)

任务执行完了,最大线程个数(4个)的线程同时进入timed_waiting 状态,到了keepAliveTime 时间,线程池中就没有线程了。如果有任务来了,在时间限定内复用线程,如果超过时间重新创建线程。任务执行完成,和之前一样!

 

你可能感兴趣的:(java,多线程,源码)