概述

首先来说一说java连接池中常用到的几个类:Executor,ExecutorService,ScheduledExecutorService

  • Executor

执行已经提交的任务对象。此接口提供了将任务提交和任务执行分离的机制。

  • ExecutorService

它是Executor的子接口,可以终止提交新的线程任务,可以中式线程池里现有的所有线程,还可以批量提交线程任务等。它的方法有很多,可以详细阅读相关的api。

  • ScheduledExecutorService

可延时执行线程任务

本文中案例中的线程实现如下:

public class ThreadDemo implements Runnable{
    private String threadName = null;
    private boolean flag = true;
    private int count;
    private int counter;
    private long suspend;
    
    /**
     * This is the constructor
     * @param threadName
     * @param count 循环次数
     * @param suspend 线程终端时间,单位毫秒
     */
    public ThreadDemo(String threadName, int count, long suspend) {
        super();
        this.threadName = threadName;
        this.count = count;
        this.suspend = suspend;
    }

    /**
     * run
     */
    @Override
    public void run() {
        while (flag) {
            try {
                Thread.sleep(suspend);
                System.out.println(threadName+"--------------"+counter);
                counter++;
                if(counter>count){
                    flag = false;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
View Code

相关文章: