Executor的三种线程的区别

Java多线程一直是java基础中非常重要的一环,最近自己在复习时,发现对其又有了新的了解,Executor可以很方方便的管理多线程,在这把它的三种不同的线程池贴出来做一个记录,有兴趣的可以看看

 Executor

package chapter21.task;

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

/**
 * Executors的使用:
 */
public class CacheedThreadPool {
    public static void main(String[] args) {
        //CachedThreadPool
        ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {
            exec.execute(new LiftOff());
        }
        //shutdown()方法:防止新任务被提交给Executor,当前线程继续运行在shutdown()被调用之前提交的所有任务,这个程序将在Executor中所有任务完成之后矜尽快退出
        exec.shutdown();

        //FixedThreadPool:有限的线程集执行所有提交的任务:在创建的时候就一次性预先执行代价高昂的线程分配
        ExecutorService execFix = Executors.newFixedThreadPool(5);

        //备注:CachedThreadPool通常会创建与所需数量相同的线程,然后在它回收旧线程的时候停止创建新线程,因此它是合理的Executor的首选,专辑由当这种方式会引发问题的时候,才需要切换到FixedThreadPool
        
        //SingleThreadExecutor:就是线程数量为1的FixedThreadPool,如果向他提供了多个任务,那么这些任务会排队,所有任务会使用相同的线程 SingleThreadExecutor会序列化所有提交给他的任务,并会维护他自己【隐藏】的悬挂任务队列
        ExecutorService execSing = Executors.newSingleThreadExecutor();
    }
}

另外,还有一种实现Callable接口的,可以有个任务返回值

package chapter21.task;

import java.util.ArrayList;
import java.util.concurrent.*;

public class CallableDemo {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        ArrayList<Future<String>> results = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            results.add(exec.submit(new TaskWithResult(i)));
        }
        for (Future<String> fs:results){
            try{
                System.out.println(fs.get());
            }catch (InterruptedException e){
                System.out.println(e);
                return;
            }catch (ExecutionException e){
                System.out.println(exec);
            }finally {
                exec.shutdown();
            }
        }
    }
}

/**
 * Callable:任务执行完成能够返回一个值
 */
class TaskWithResult implements Callable {

    private int id;

    public TaskWithResult(int id) {
        this.id = id;
    }

    @Override
    public String call() {
        return "result of TaskWithResult" + id;
    }
}

重点是理解Future的作用,以后有时间再给大家补上

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值