概述

首先来说一说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

相关文章:

  • 2022-02-18
  • 2022-01-16
  • 2022-12-23
  • 2022-02-08
  • 2021-12-28
  • 2021-07-26
  • 2021-05-30
  • 2021-07-11
猜你喜欢
  • 2021-07-31
  • 2021-11-13
  • 2021-11-09
  • 2021-07-01
  • 2021-05-29
  • 2022-12-23
相关资源
相似解决方案