我的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
}
我添加了synchronized关键字,但它一次只处理一个请求导致性能问题,因为每个下一个线程都必须等到它完成。请帮帮我。
答案 0 :(得分:2)
您可以在执行逻辑内部使用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!
注意强>
请参阅重用的线程名称,这些是在池中分配了空闲线程的新提交任务。
答案 1 :(得分:1)
您可以创建Executor
,并使用Semaphore
限制其接受的任务数量。像这样:
private final Semaphore semaphore = new Semaphore(4);
ThreadPoolExecutor tp= new ThreadPoolExecutor(...){
public void execute(Runnable r){
semaphore.acquire();
super.execute(r);
}
public void afterExecute(Runnable r, Thread t){
semaphore.release();
super.afterExecute(r,t);
}
};
答案 2 :(得分:1)
信号量。在里面。有5个单位,并且线程在函数顶部等待,并在结束时发出信号。
答案 3 :(得分:0)
您可以使用限制为5个主题的ThreadPool
。在这里,您创建一个ThreadPool并向其提交一个新线程,以便在您的类上工作。它只允许您配置的最大线程数同时工作。如果有超过配置数量的线程,则必须等到某个工作线程完成它的任务。
答案 4 :(得分:0)
创建一个固定大小的thread pool来执行此操作。