Sajith Rupasinghe
Sajith Rupasinghe

Reputation: 343

Return a value from a thread after it finish execution

I have a Java Thread that I'm using to upload some files asynchronously to a server. I need my thread to return some values after completing the upload. So as mentioned in this example I have created another method that return some value and access that method from the main class. As for my requirement I have to upload multiple files so if the thread runs for a second time it hangs on t1.join(). So I need to know what would be the best method to resolve my issue.?

My upload thread:

public class UploadThread extends Thread {

    public UploadThread() {

    }

    @Override
    public void run() {

        try {
            //Upload happens here

        } catch (IOException ex) {
            Logger.getLogger(UploadThread.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    //Method use to return upload status
    public String status() {
        //verify upload has completed
        return "Upload successful";
    }
}

Calling thread from main class:

//Calling upload thread multiple times depends on no of files
for (int i = 0; i < fileList.length; i++) {

    UploadThread t1 = new UploadThread();
    t1.start();
    t1.join();
    String status = t1.status();
    System.out.println(status);

}

Upvotes: 1

Views: 2312

Answers (1)

Sajith Rupasinghe
Sajith Rupasinghe

Reputation: 343

I have implemented Future interface with callbacks as follows. it resolved my issue.

Callable implementation:

public class Upload implements Callable<Integer> {
    public Upload() {  
    }

    @Override
    public Integer call() {
        try {
            //Upload happens here. after completing returns value as required.  
            return 0;
        }
    }    
}

Execute callable from main class:

for (int i=0; i<fileList.length;i++) {
    Upload up = new Upload();
    FutureTask<Integer> future = new FutureTask(up);
    future.run();
    int result = future.get();
}

I followed the example from here

Upvotes: 1

Related Questions