Java之线程池

package com.company;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;

class th1 implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"正在执行");
    }
}
class th2 implements ThreadFactory{
    public Thread newThread(Runnable r){
        return new Thread(r);
    }
}
public class Main{
    public static void main(String[] args){
        //使用 ExecutorsService Executors.newFixedThreadPool(int num)方法创建线程数为num的线程池
        ExecutorService ex=Executors.newFixedThreadPool(3);
        ex.submit(new th1()); //在线程池里创建并启动一个线程
        ex.submit(new th1());
        ex.submit(new th1());
        ex.shutdown();//关闭整个线程池,如果再使用shutdown后还继续调用该线程池的有关方法,则会报错
        //使用Thread newThread(Runnable r)创建线程工厂
        ExecutorService ex1=Executors.newFixedThreadPool(2,new th2());
        for(int i=1;i<4;i++){
            ex1.submit(new th1());
        }
        ex1.shutdown();
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值