Frage

What I'm trying to do here is to upload files one by one. For example, if my file list contains 2 files ready to upload, I want to upload the second file once the first is uploaded and created.

Actually, I loop the file list and upload the file from each iteration whitout waiting the last upload to finish.

Here is an idea of what I'm excepecting :

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 is a bean with getters and setters (setFile,getFile,isCreated....).

When the upload is over and the file is created ( HttpResponseCode=201), fileContainer.isCreated=true. Initially, isCreated=false;

I hope that I'm clear enough ! So is it possible to do that ?

Thanks in advance !

Ismail

War es hilfreich?

Lösung

So you basically want to continue the execution only after the th thread is finished? Just don't run it in a separate thread, but rather:

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

    // continues after the file is uploaded
}

If you want to keep this in a separate thread after all (as you said in a comment), then execute the whole loop in the background:

    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();

Andere Tipps

You should set the notify() in the run method of Thread th so after the new thread finish the upload, it will notify the waited thread.

Or I see that you want your main thread to wait until the upload process completed, so why don't you simply make your program single threaded.
I mean don't initiate the upload process in a new thread, because the default behavior then is wait until the current upload is finished then start the second upload and that is what you want.

Do like this

 while(true){
     if(fileContainer.isCreated()){
       break;
     }
 }      
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top