java多线程创建方式4种:方式三

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 *  创建线程的方式四:使用线程池
 *
 *  好处:
 *      1、提高响应速度(减少了创建新线程的时间)
 *      2、降低资源消耗(重复利用线程池中线程,不需要每次都创建)
 *      3、便于线程管理
 *          corePoolSize:核心大小
 *          maximumPoolSize:最大线程数
 *          keepAliveTime:线程没有任务时,最多保持多长时间后终止
 *
 * @author dqp
 * @create 2021-12-20 0:54
 */

class NumberThread1 implements  Runnable{
    @Override
    public void run() {
        for (int i = 0; i <=100 ; i++) {
            if(i%2==0){
                System.out.println(Thread.currentThread().getName()+":"+i);
            }
        }
    }
}

class NumberThread2 implements  Runnable{
    @Override
    public void run() {
        for (int i = 0; i <=100 ; i++) {
            if(i%2!=0){
                System.out.println(Thread.currentThread().getName()+":"+i);
            }
        }
    }
}



public class ThreadPool {
    public static void main(String[] args) {
        //1、提供指定线程数量的线程池
        ExecutorService service = Executors.newFixedThreadPool(10);
        ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;
        //设置线程池的属性
//        System.out.println(service.getClass());
//        service1.setCorePoolSize(15);
//        service1.setKeepAliveTime();

        //2、执行指定的线程的操作。需要提供Runnable接口或Callable接口实现类的对象
        service.execute(new NumberThread1());//适用于使用Runnable
        service.execute(new NumberThread2());//适用于使用Runnable
//        service.submit(Callable callable);//适用于使用Callable

        //关闭连接池
        service.shutdown();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值