gpt4 book ai didi

Java如何限制作用于方法的线程数量

转载 作者:行者123 更新时间:2023-12-01 18:14:01 25 4
gpt4 key购买 nike

我的 Web 应用程序中有 java 方法执行繁重的文件操作。问题是,如果超过 5 个线程同时出现(将在测试阶段出现),它就会崩溃。我的意思是它无法处理大流量。

这就是为什么我想一次最多处理 5 个请求,如果第 6 个请求到来,它将等待直到前 5 个请求之一完成

public  synchronized void add(int value){
File a=new File("D:/heavyFile1");
File b=new File("D:/heavyFile2");
File c=new File("D:/heavyFile3");
//operation on file
}

我添加了同步关键字,但它一次只处理一个请求,导致性能问题,因为每个下一个线程都必须等待它完成。请帮助我。

最佳答案

您可以在执行逻辑内部使用Executor.newFixedThreadPool 习惯用法。

完整示例如下:

public class Main {

public static void main(String[] args) throws Exception {
Main m = new Main();
// simulating a window of time where your method is invoked continuously
for (int i = 0; i < 11; i++) {
m.doSomething();
}
// shutting down executor when done
m.terminate();
}

ExecutorService executor = Executors.newFixedThreadPool(5);

// internally submits a new task to the executor
public void doSomething() {
executor.submit(new Runnable() {
@Override
public void run() {
long wait = ThreadLocalRandom.current().nextLong(2000);
try {
System.out.printf(
"%s is sleeping for %dms.%n",
Thread.currentThread().getName(),
wait
);
Thread.sleep(wait);
}
catch (InterruptedException ie) {
// suppressed
}
System.out.printf(
"%s is doing something!%n",
Thread.currentThread().getName()
);
}
});
}

public void terminate() throws Exception {
executor.shutdown();
}
}

输出

会有所不同,具体如下:

pool-1-thread-1 is sleeping for 1533ms.
pool-1-thread-4 is sleeping for 784ms.
pool-1-thread-3 is sleeping for 684ms.
pool-1-thread-5 is sleeping for 1375ms.
pool-1-thread-2 is sleeping for 1717ms.
pool-1-thread-3 is doing something!
pool-1-thread-3 is sleeping for 1252ms.
pool-1-thread-4 is doing something!
pool-1-thread-4 is sleeping for 301ms.
pool-1-thread-4 is doing something!
pool-1-thread-4 is sleeping for 1140ms.
pool-1-thread-5 is doing something!
pool-1-thread-5 is sleeping for 1454ms.
pool-1-thread-1 is doing something!
pool-1-thread-1 is sleeping for 1594ms.
pool-1-thread-2 is doing something!
pool-1-thread-2 is sleeping for 227ms.
pool-1-thread-3 is doing something!
pool-1-thread-2 is doing something!
pool-1-thread-4 is doing something!
pool-1-thread-5 is doing something!
pool-1-thread-1 is doing something!

注意

查看重用的线程名称,这些是新提交的任务,并在池中分配了一个空闲线程。

关于Java如何限制作用于方法的线程数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30840829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com