gpt4 book ai didi

java - 在for循环java中的下一次迭代之前等待()

转载 作者:行者123 更新时间:2023-11-30 11:23:46 26 4
gpt4 key购买 nike

我在这里要做的是一个一个地上传文件。例如,如果我的文件列表包含 2 个准备上传的文件,我想在第一个文件上传并创建后上传第二个文件。

实际上,我循环文件列表并从每次迭代上传文件,而无需等待最后一次上传完成。

这是我所期望的想法:

for(FileContainerBean fileContainer:fileContainerList){

FileUpload fileUpload=new FileUpload(fileContainer.getFile());
Thread th=new Thread(fileUpload);
th.start();

//Now i want here to wait beafore moving to the next iteration

while(!fileContainer.isCreated(){
wait();
}
if(fileContainer.isCreated(){
notify();
}
}

fileContainer 是一个带有 getter 和 setter 的 bean(setFile、getFile、isCreated....)。

当上传结束并创建文件时 (HttpResponseCode=201),fileContainer.isCreated=true。最初,isCreated=false;

我希望我已经足够清楚了!那么有可能这样做吗?

提前致谢!

伊斯梅尔

最佳答案

所以您基本上只想在第 th 线程完成后继续执行?只是不要在单独的线程中运行它,而是:

for(FileContainerBean fileContainer:fileContainerList){
FileUpload fileUpload=new FileUpload(fileContainer.getFile());
fileUpload.run();

// continues after the file is uploaded
}

如果你想把它放在一个单独的线程中(正如你在评论中所说),那么在后台执行整个循环:

    Runnable uploadJob = new Runnable() { 
public void run() {
for(FileContainerBean fileContainer:fileContainerList){
FileUpload fileUpload=new FileUpload(fileContainer.getFile());
fileUpload.run();
// continues after the file is uploaded
}
}
};

new Thread(uploadJob).start();

关于java - 在for循环java中的下一次迭代之前等待(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20998793/

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