java - 根据时间限制运行线程

标签 java multithreading scheduled-tasks threadpool

我想每秒最多启动40个http请求,并在1秒后,从它自己的队列(例如threadpooltaskexecutor的阻塞队列)中运行另外40个http请求。我正在为此要求寻找执行程序或线程池实现。

有什么建议吗?

谢谢

里阿里

编辑:由于明显的原因,修复率效率不高。当队列项目一个接一个地开始时,队列后面的项目将刚刚开始,但是已经启动了一段时间的项目可能会完成。

额外的编辑:问题是在一秒钟内只调用40个请求,没有激活最大40个。可能在另一秒为80,但在1秒钟内应该只有40个新创建的连接。

最佳答案

一种实现方法是使用另一种体系结构,这将使过程变得更加轻松。

1)创建一个实现可运行对象的Thread类。
2)它以您要发出的HTTP请求列表<>()作为参数
3)使run()函数循环整个列表(大小为40)
4)让线程存活一秒钟。

这是一个示例示例:

class MyClass extends Thread

private ArrayList<...> theList;

public MyClass(ArrayList<..> theList){
    this.theList = theList;
}

public void run(){
    //Here, you simply want to loop for the entier list (max 40)
    for(Req r: theList){
        r.sendRequest()
    )
}

public statc void main(String args[]){
  //Create an instance of your thread:
  MyClass t = new MyClass(ReqList<..>());

  //Now that you have your thread, simply do the following:

  while(true){
     t = new MyClass( (insert your new list));
     t.start();
     try{
       Thread.sleep(1000);
     }catch(Exception e){

     }
  )



}
}

那里有

关于java - 根据时间限制运行线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25916745/

相关文章:

java - 视频培训计划

c# - 在 ui 线程中执行委托(delegate)(使用消息泵)

java - 在并发环境中创建单例的最佳实践?

java - JSF 每 2 秒从系统动态加载属性文件

Java方法同步使用不当?

java - 是否有一个好的 "standard"Java 接口(interface)用于 XML 和 JSON 读取器/写入器?

python - Flask-SQLALchemy 在特定时间后自动更新记录

powershell - MS Exchange 2010:cmdlet无法作为计划任务正确执行

java - 使用有界泛型编译 lambda 时出错

vb.net - 在 vb.net 中使用线程的进度 "bar"