When a thread is done, how to notify the main thread?
Solution 1
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();
Solution 2
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.
CaiNiaoCoder
I am a Java developer. I live in China. I like playing football My English is not good.
Updated on August 01, 2022Comments
-
CaiNiaoCoder over 1 year
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();
-
avalancha about 10 yearswouldn't this mean that the
UploadThread
(which you say performs some callback) invoked the theonUploadComplete
on the worker thread and not on the main thread? The print you outline in your example will not be done on the main thread as far as I can see -
aioobe about 10 yearsThat's right. It was a while ago I wrote the answer. If I rewrote it today, I would strongly encourage the reader to use executor services, callables and futures.