CaiNiaoCoder
CaiNiaoCoder

Reputation: 3319

When a thread is done, how to notify the main thread?

I use FTP raw commands to upload file to a FTP server, I start a new thread to send file via socket in my code. when the newly started thread finished sending file I want to output some message to console, how can I make sure the thread have finished it's work ? here is my code:

TinyFTPClient ftp = new TinyFTPClient(host, port, user, pswd);
ftp.execute("TYPE A");
String pasvReturn = ftp.execute("PASV");
String pasvHost = TinyFTPClient.parseAddress(pasvReturn);
int pasvPort = TinyFTPClient.parsePort(pasvReturn);
new Thread(new FTPFileSender(pasvHost, pasvPort, fileToSend)).start();

Upvotes: 7

Views: 16784

Answers (2)

aioobe
aioobe

Reputation: 421060

how can I make sure the thread have finished it's work ?

You do call Thread.join() like this:

...
Thread t = new Thread(new FTPFileSender(pasvHost, pasvPort, fileToSend));
t.start();

// wait for t to finish
t.join();

Note however that Thread.join will block until the other thread has finished.

A better idea is perhaps to encapsulate the upload-thread in a UploadThread class which performs some callback when it's done. It could for instance implement an addUploadListener and notify all such listeners when the upload is complete. The main thread would then do something like this:

UploadThread ut = new UploadThread(...);
ut.addUploadListener(new UploadListener() {
    public void uploadComplete() {
        System.out.println("Upload completed.");
    }
});

ut.start();

Upvotes: 10

Waldheinz
Waldheinz

Reputation: 10487

For what you are trying to do, I see at least three ways to accomplish:

  • you could just let the uploading thread itself print the logging message or
  • in some other thread, you can join the upload thread. Using this approach you could do some other work before calling join, otherwise there is no gain from doing it in a separate thread.
  • you can implement some kind of listener, so an uploading Thread informs all registered listeners about it's progress. This is the most flexible solution, but also the most complex.

Upvotes: 2

Related Questions