Java线程池实战

一 使用newSingleThreadExecutor创建一个只包含一个线程的线程池

1 代码

import java.util.concurrent.*;
public class executorDemo
{
    public static void main( String[] args )
    {       
       ExecutorService executor = Executors.newSingleThreadExecutor();
       executor.submit(() -> {
           String threadName = Thread.currentThread().getName();
           System.out.println("Hello " + threadName);
       });  
    }
}

2 运行

Hello pool-1-thread-1

二 含有终止方法的线程池

1 代码

import java.util.concurrent.*;

public class executorShutdownDemo {
    public static void main( String[] args ) {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(() -> {
            String threadName = Thread.currentThread().getName();
            System.out.println("Hello " + threadName);
        });
        try {
            TimeUnit.SECONDS.sleep(3);
            System.out.println("尝试关闭线程执行器...");
            executor.shutdown();
            executor.awaitTermination(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            System.err.println("关闭任务被中断!");
        } finally {
            if (!executor.isTerminated()) {
                System.err.println("取消未完成的任务");
                executor.shutdownNow();
            }

            System.out.println("任务关闭完成");
        }
    }
}

2 运行

Hello pool-1-thread-1
尝试关闭线程执行器...
任务关闭完成

3 说明

shutdown只是将线程池的状态设置为SHUTWDOWN状态,正在执行的任务会继续执行下去,没有被执行的则中断。

shutdownNow则是将线程池的状态设置为STOP,正在执行的任务则被停止,没被执行任务的则返回。

举个工人吃包子的例子:一个厂的工人(Workers)正在吃包子(可以理解为任务)。

假如接到shutdown的命令,那么这个厂的工人们则会把手头上的包子给吃完,没有拿到手里的笼子里面的包子则不能吃!

而如果接到shutdownNow的命令以后呢,这些工人们立刻停止吃包子,会把手头上没吃完的包子放下,更别提笼子里的包子了。

awaitTermination(long timeOut, TimeUnit unit)

当前线程阻塞,直到

  • 等所有已提交的任务(包括正在跑的和队列中等待的)执行完

  • 或者等超时时间到

  • 或者线程被中断,抛出InterruptedException

然后返回true。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值