启动线程的四种方式

1、继承Thread

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("MyThread");
    }
}

    public static void test(){
        MyThread thread = new MyThread();
        thread.start();
    }

2、实现Runnable接口

class MyRunnable implements Runnable {

    @Override
    public void run() {
        System.out.println("MyRunnable");
    }
}

    public static void test2(){
        MyRunnable runnable = new MyRunnable();
        new Thread(runnable).start();
    }

3、实现Callable接口 + FeatureTask 可以拿到任务的返回结果

class MyCallable implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        return 10/2;
    }
}

public static void test3() throws ExecutionException, InterruptedException {
        MyCallable runnable = new MyCallable();
        FutureTask<Integer> task = new FutureTask<>(runnable);
        new Thread(task).start();
        System.out.println(task.get());
    }

4、使用线程池,直接给线程池提交任务

 public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.acc = System.getSecurityManager() == null ?
                null :
                AccessController.getContext();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

参数解释:
corePoolSize:核心线程数
maximumPoolSize:最大线程数
keepAliveTime:多余核心线程数得线程存活时间
unit:时间单位
workQueue:阻塞队列,如果任务很多,可以先把任务放到队列中,当线程执行完当前任务会自动从队列获取新任务
threadFactory:线程得创建工厂
handler:如果线程满了。按照我们指定得拒绝策略拒绝执行任务

线程池执行顺序:
1、线程池创建,创建核心线程,准备接收任务
2、没有空闲核心线程,就把任务放到队列中
3、队列满了之后,在最大线程数范围内创建新得线程处理任务
4、最大线程数也满了,就开始使用拒绝策略处理任务
5、任务执行完,除了核心线程,空闲得线程会在存活时间之后释放

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值