Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 545
CaiNiaoCoder Avatar asked May 30 '11 08:05

CaiNiaoCoder


1 Answers

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();
like image 98
aioobe Avatar answered Sep 19 '22 15:09

aioobe