Java 限制部分代码的活动线程数
我有一个多线程Java程序,它主要与带有代理的Apache HTTP组件一起工作。然而,代码中有一个部分与上传照片有关,这占用了相当多的带宽,如果我不限制该部分的并发线程,我将开始超时。现在这就是我所拥有的,它只允许1个线程访问上传照片的代码部分Java 限制部分代码的活动线程数,java,multithreading,Java,Multithreading,我有一个多线程Java程序,它主要与带有代理的Apache HTTP组件一起工作。然而,代码中有一个部分与上传照片有关,这占用了相当多的带宽,如果我不限制该部分的并发线程,我将开始超时。现在这就是我所拥有的,它只允许1个线程访问上传照片的代码部分 public class CommonUtil { private static final Object _uploadPhoto = new Object(); public void start(){ //oth
public class CommonUtil {
private static final Object _uploadPhoto = new Object();
public void start(){
//other code
synchronized (_uploadPhoto) {
//all code related to photo upload
}
//other code
}
}
<> P>上面的代码的问题是它不考虑与线程连接的当前代理。我希望我的程序能够不允许超过线程上传照片,只有当它是相同的代理
在程序中,我确实能够检查线程当前正在使用哪个代理
account.getProxyId()
假设有三个不同的代理服务器正在使用。在photoupload部分,具有不同代理的线程可以使用它,但如果它们具有相同的代理,则不能使用它 遗嘱执行人
使用Java框架为Java的更高版本制定任务计划。看
线程池
实例化尽可能多的线程池支持的执行器。跟踪每个代理的一个执行者。任何特定代理的任务都会分配给同一执行者
每个执行器都由其自己的线程池提供支持,并具有您指定的任何线程限制。当分配的任务超过当前可以处理的数量时,执行器会将它们缓冲起来,以便在线程可用时分配
示例代码
提前建立executor服务对象,每个代理一个
ExecutorService execForProxyA = Executors.newFixedThreadPool( 3 ) // Three threads maximum at a time working on tasks headed for proxy "A".
ExecutorService execForProxyB = Executors.newFixedThreadPool( 2 ) // Two threads maximum at a time working on tasks headed for proxy "B".
ExecutorService execForProxyC = Executors.newFixedThreadPool( 5 ) // Five threads maximum at a time working on tasks headed for proxy "C".
定义任务
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println( "Hello World!" ) ;
}
};
或者使用
将任务分配给用于所需代理的executor服务
您将获得一个Future
对象,可用于跟踪任务的进度和完成情况
Future future = execForProxyA.submit( r ) ; // Optionally capture the returned `Future` object.
重要提示:确保在应用程序中适当关闭executor服务。否则,支持线程池的运行时间可能会比您预期的长,甚至可能在您的应用程序退出之后。这绝对是专用执行器的情况。
Future future = execForProxyA.submit( r ) ; // Optionally capture the returned `Future` object.