Java 使用ThreadPoolExecutor时出现UI问题
我正在使用ThreadPoolExecutor实现多线程 基本上每个线程都分配了一个文件,需要上传到服务器。 每次成功上载后,服务器都会发出通知 下面的代码生成线程并将文件分配给它们Java 使用ThreadPoolExecutor时出现UI问题,java,multithreading,applet,Java,Multithreading,Applet,我正在使用ThreadPoolExecutor实现多线程 基本上每个线程都分配了一个文件,需要上传到服务器。 每次成功上载后,服务器都会发出通知 下面的代码生成线程并将文件分配给它们 Random random = new Random(); ExecutorService executor = new ThreadPoolExecutor(5, 5, 50000L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<R
Random random = new Random();
ExecutorService executor = new ThreadPoolExecutor(5, 5, 50000L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(400));
int waitTime = 100;
while (it.hasNext()) {
int time = random.nextInt(1000);
waitTime += time;
newFile = new File((String) it.next());
executor.execute(new Runnable() {
@Override
public void run() {
processFile(newFile);
}
});
try {
Thread.sleep(waitTime);
} catch (Exception e) {
}
}
try {
Thread.sleep(waitTime);
executor.shutdown();
executor.awaitTermination(waitTime, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
}
Random Random=new Random();
ExecutorService executor=新的ThreadPoolExecutor(5,5,50000L,TimeUnit.ms,新的ArrayBlockingQueue(400));
int waitTime=100;
while(it.hasNext()){
int time=random.nextInt(1000);
waitTime+=时间;
newFile=新文件((字符串)it.next());
executor.execute(新的Runnable(){
@凌驾
公开募捐{
进程文件(newFile);
}
});
试一试{
睡眠(等待时间);
}捕获(例外e){
}
}
试一试{
睡眠(等待时间);
executor.shutdown();
执行器等待终止(等待时间,时间单位毫秒);
}捕捉(中断异常e){
}
我已经创建了一个用于呈现UI的Java小程序。
每次通知后,我都会更新Java小程序窗口中的文件状态,在该窗口中,从processFile()调用updateUI()
在使用ExecutorService(建议在JavaV5.0及以上版本上处理多线程)之前,我使用了一个Thread类来创建文件上传功能的threads&wait notify。显示每个文件更新状态的UI在使用Thread类时正确呈现,但在使用ExecutorService时,所有文件都会上载(功能正常),但UI会挂起
成功上载每个文件后,需要更新每个文件的文件上载状态
欢迎提供任何建议/提示。如果希望从非EDT线程(调用事件处理程序等的事件线程)更新UI,则需要使用 你永远不应该在EDT上睡觉,也不应该阻止它,因为这是一个确保一切都有反应的设备 但是,最好使用,因为它实现了一些特定于使用需要更新gui的后台线程的事情 使用swingWorker,您的代码将
while (it.hasNext()) {
final File newFile = new File((String) it.next());
SwingWorker<Void,Void> work = new SwingWorker<Void,Void>(){
@Override
public Void doInBackground() {
processFile(newFile);//do **not** call updateUI() in here
return null;
}
@Override
protected void done(){//this gets called after processFile is done on the EDT
updateUI();
}
}).execute();
}
while(it.hasNext()){
final File newFile=新文件((字符串)it.next());
SwingWorker工作=新SwingWorker(){
@凌驾
公共无效doInBackground(){
processFile(newFile);//不要在这里**调用updateUI()
返回null;
}
@凌驾
protected void done(){//在EDT上完成processFile后调用此函数
updateUI();
}
}).execute();
}
感谢您的回复。我想在上传文件时实现多线程,所以执行器的实现也很重要。上面的代码不包含这方面的任何引用。如果您只是消除了所有休眠和等待终止,只要文件不超过400个(那么添加新作业将失败),您就应该没事(您仍然应该关闭执行器以避免线程泄漏)