Java新手学习 2021-2-24 记录每天学习内容(如有侵权请联系删除!!!)【待完善,先保命,看框架,后续整理】

2021-2-24

1.线程状态

在这里插入图片描述

2.线程池(newCachedThreadPool,newFixedThreadPool)

在这里插入图片描述

package com.wc.executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 * @author wc
 * @Date: 2021/02/25/9:14
 */
public class ExecutorDemo {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
        //创建一个默认的线程池,默认的线程池为空,默认最多容纳int类型的最大值
        //ExecutorService executorService = Executors.newCachedThreadPool();
        
        //创建指定线程数量的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        executorService.submit(()->{
    
    
            //Thread.currentThread().getName()获取线程名称
            System.out.println(Thread.currentThread().getName());
        });
        /*如果在这睡眠两秒,下一次线程开启将还会是线程1,如果线程池有数据
        * 将直接从线程池拿有的数据*/
        Thread.sleep(2000);
        executorService.submit(()->{
    
    
            //Thread.currentThread().getName()获取线程名称
            System.out.println(Thread.currentThread().getName());
        });
        //关闭线程池
        executorService.shutdown();
    }
}

3.线程池ThreadPoolExecutor

在这里插入图片描述
在这里插入图片描述

package com.wc.executor;
import java.util.concurrent.*;

/**
 * @author wc
 * @Date: 2021/02/25/9:14
 */
public class ExecutorDemo1 {
    
    
    public static void main(String[] args)  {
    
    
        /*1.参数一:核心线程数量
        * 2.参数二:最大线程数
        * 3.参数三:空闲线程存活最大时间
        * 4.参数四:时间单位
        * TimeUnit.SECONDS  可用枚举类TimeUtils
        * 5.参数五:任务队列
        * 阻塞队列
        * 6.参数六:创建线程工厂
        *Executors.defaultThreadFactory()默认线程池
        * 7.参数七:任务的拒绝策略
        *new ThreadPoolExecutor.AbortPolicy()
        * */
        ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor(2, 5, 2, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
        threadPoolExecutor.submit(new RunnableImpl());
        threadPoolExecutor.submit(new RunnableImpl());
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_49221590/article/details/114030491