java 线程池

来源:互联网 发布:视频剪辑配乐软件 fcp 编辑:程序博客网 时间:2024/05/18 02:31

说道线程池,大家肯定想到ExecutorService类,事实上,在java.util.concurrent包中的ExecutorService的实现就是一个线程池的实现。那,我们为什么使用线程池呢?

1:提高效率 创建好一定数量的线程放在池中,等需要使用的时候就从池中拿一个,这要比需要的时候创建一个线程对象要快的多。

2:方便管理 可以编写线程池管理代码对池中的线程统一进行管理,比如说系统启动时由该程序创建100个线程,每当有请求的时候,就分配一个线程去工作, 如果刚好并发有101个请求,那多出的这一个请求可以排队等候,避免因无休止的创建线程导致系统崩溃.

那下面我们就来看看,怎么创建线程池?

(1)ExecutorService executorService1 = Executors.newSingleThreadExecutor();
(2)ExecutorService executorService2 = Executors.newFixedThreadPool(10);
(3)ExecutorService executorService3 = Executors.newScheduledThreadPool(10);

ExecutorService 使用方法又有哪些呢?

execute(Runnable)
submit(Runnable)
submit(Callable)
invokeAny(…)
invokeAll(…)

那接下来我们依次看看这些方法?

1.execute()方法

ExecutorService executorService=Executors.newSingleThreadExecutor();    executorService.execute(new Runnable() {        public void run() {            System.out.println("newSingleThreadExecutor。。。。。");        }    });    executorService.shutdown();

使用这种方式没有办法获取执行Runnable之后的结果。

2.submit(Runnable)方法

    ExecutorService executorService2=Executors.newFixedThreadPool(1);    Future future = executorService2.submit(new Runnable() {        public void run() {            // TODO Auto-generated method stub            System.out.println("newFixedThreadPool。。。。。");        }    });    executorService2.shutdown();    try {        System.out.println("future.get=" + future.get());    } catch (Exception e) {        // TODO Auto-generated catch block        e.printStackTrace();    }

方法submit(Runnable)同样接收一个Runnable的实现作为参数,但是会返回一个Future对象。这个Future对象可以用于判断Runnable是否结束执行。

3.submit(Callable)方法

ExecutorService executorService3 = Executors.newCachedThreadPool();    Future future2 = executorService3.submit(new Callable<String>() {        public String call() throws Exception {            // TODO Auto-generated method stub            System.out.println("newCachedThreadPool。。。。。");            return "wangwei";        }    });    try {        System.out.println("future2.get=" + future2.get());    } catch (Exception e) {        // TODO Auto-generated catch block        e.printStackTrace();    }

输出结果为:
newCachedThreadPool。。。。
wangwei

方法submit(Callable)和方法submit(Runnable)比较类似,但是区别则在于它们接收不同的参数类型。Callable的实例与Runnable的实例很类似,但是Callable的call()方法可以返回一个结果。方法Runnable.run()则不能返回结果。

Callable的返回值可以从方法submit(Callable)返回的Future对象中获取。

4.inVokeAny()方法

ExecutorService executorService4 = Executors.newSingleThreadExecutor();Set<Callable<String>> callables = new HashSet<Callable<String>>();callables.add(new Callable<String>() {    public String call() throws Exception {        return "lihuan1";    }});callables.add(new Callable<String>() {    public String call() throws Exception {        return "lihuan12";    }});callables.add(new Callable<String>() {    public String call() throws Exception {        return "lihuan13";    }});String result = null;    try {        result = executorService4.invokeAny(callables);    } catch (Exception e) {        e.printStackTrace();    }System.out.println("result = " + result);executorService.shutdown();

方法invokeAny()接收一个包含Callable对象的集合作为参数。调用该方法不会返回Future对象,而是返回集合中某一个Callable对象的结果,而且无法保证调用之后返回的结果是哪一个Callable,只知道它是这些Callable中一个执行结束的Callable对象。

5.invokeAll()方法

ExecutorService executorService5 = Executors.newSingleThreadExecutor();Set<Callable<String>> callables = new HashSet<Callable<String>>();callables.add(new Callable<String>() {    public String call() throws Exception {        return "lihuan1";    }});callables.add(new Callable<String>() {    public String call() throws Exception {        return "lihuan2";    }});callables.add(new Callable<String>() {    public String call() throws Exception {        return "lihuan3";    }});List<Future<String>> futures = executorService5.invokeAll(callables);List<Future<String>> futures = null;    try {        futures = executorService.invokeAll(callables);        for(Future<String> future : futures){            System.out.println("future.get = " + future.get());        }    } catch (Exception e) {        e.printStackTrace();    }    executorService.shutdown();

输出结果为:
future.get = lihuan3
future.get = lihuan2
future.get = lihuan1

方法invokeAll()接收一个包含Callable对象的集合作为参数,并且返回包含所有Future对象的集合,你可以通过这个返回的集合来管理每个Callable的执行结果。需要注意的是,任务有可能因为异常而导致运行结束,所以它可能并不是真的成功运行了。但是我们没有办法通过Future对象来了解到这个差异。

ExecuteService 服务的关闭

shutdown()和shutdownNow()
shutdown():执行后不再接收新任务(则不能再往线程池中添加任何任务),如果线程池里面有任务,就执行完;通常shutdown之后调用awaitTermination(long timeout, TimeUnit unit),作用是:后者会阻塞当前线程,等待线程池中剩余任务执行完,然后继续往下执行。如果不适用await,那么shutdown之后,很可能导致剩余任务得不到执行(整个程序退出),或是执行出现异常(某些资源被释放之类)。

(注: boolean awaitTermination(long timeout, TimeUnit unit)//等待(阻塞)直到关闭或最长等待时间或发生中断,timeout - 最长等待时间 ,unit - timeout 参数的时间单位 如果此执行程序终止,则返回 true;如果终止前超时期满,则返回 false )

shutdownNow():执行后不再接受新任务,如果有等待任务,移出队列;有正在执行的,尝试停止之;

1 0
原创粉丝点击