并发编程(2)

2019-11-26  本文已影响0人  禾叶super

今天说一下使用java.util.concurrent包下的ExecutorService来管理线程的方法。
依然从实例开始
实例1

public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName()+":before");
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+":thread");
            }
        });
        executorService.shutdown();
        System.out.println(Thread.currentThread().getName()+":after");
    }

这段代码和昨天在并发编程(1)中使用Thread创建线程达到的效果是一样的。


image.png

那么为何要使用线程池来管理线程呢。这是因为线程也是资源,通过Thread类创建的线程是不可重用的,我们无法重新启动线程。创建线程的多少与运行程序的主机的CPU核数有关。并发编程正是利用了多核CPU的处理能力,真正的多线程只能在多核CPU上实现。因此创建的线程并不是越多越好。
通过ExecutorService 来管理线程,可以把线程的创建和执行过程分离开来。这样线程池中的线程可以被重复利用。ExecutorService 可以按需配置线程池的类型,单线程的,带缓存的,基于优先级的等等都可以通过代码配置。

// 获取线程执行后的返回值
executorService.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                
                return "thread1";
            }
        });

如果想了解更多用法,参考链接:https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html

上一篇 下一篇

猜你喜欢

热点阅读