java 当一个线程完成后,如何通知主线程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6173835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When a thread is done, how to notify the main thread?
提问by CaiNiaoCoder
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:
我使用 FTP 原始命令将文件上传到 FTP 服务器,我在我的代码中启动了一个新线程通过套接字发送文件。当新启动的线程完成发送文件时,我想向控制台输出一些消息,如何确保线程已完成它的工作?这是我的代码:
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();
回答by aioobe
how can I make sure the thread have finished it's work ?
我怎样才能确保线程已经完成它的工作?
You do call Thread.join()
like this:
你确实这样打电话Thread.join()
:
...
Thread t = new Thread(new FTPFileSender(pasvHost, pasvPort, fileToSend));
t.start();
// wait for t to finish
t.join();
Note however that Thread.join
will blockuntil the other thread has finished.
但是请注意,这Thread.join
将阻塞,直到另一个线程完成。
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
类中,该类在完成后执行一些回调。例如,它可以实现addUploadListener
并在上传完成时通知所有此类侦听器。然后主线程会做这样的事情:
UploadThread ut = new UploadThread(...);
ut.addUploadListener(new UploadListener() {
public void uploadComplete() {
System.out.println("Upload completed.");
}
});
ut.start();
回答by Waldheinz
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 jointhe upload thread. Using this approach you could do some other work beforecalling
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.
- 您可以让上传线程本身打印日志消息或
- 在其他一些线程中,您可以加入上传线程。使用这种方法你可以在调用之前做一些其他的工作
join
,否则在单独的线程中做它没有任何好处。 - 您可以实现某种侦听器,因此上传会
Thread
通知所有已注册的侦听器其进度。这是最灵活的解决方案,但也是最复杂的。