【发布时间】:2013-10-26 04:27:41
【问题描述】:
我正在尝试将线程池中的任务排入队列,以便在工作人员空闲时立即执行,我发现了各种示例,但在所有情况下,这些示例都已设置为为每个工作人员使用一个新的 Worker 实例工作,我想要持久的工人。
我正在尝试制作一个 ftp 备份工具,我可以使用它,但由于单一连接的限制,它速度很慢。我理想中想要做的是有一个单一的连接来扫描目录并建立一个文件列表,然后四个工作人员来下载所述文件。
这是我的 FTP 工作者的示例:
public class Worker implements Runnable {
protected FTPClient _ftp;
// Connection details
protected String _host = "";
protected String _user = "";
protected String _pass = "";
// worker status
protected boolean _working = false;
public Worker(String host, String user, String pass) {
this._host = host;
this._user = user;
this._pass = pass;
}
// Check if the worker is in use
public boolean inUse() {
return this._working;
}
@Override
public void run() {
this._ftp = new FTPClient();
this._connect();
}
// Download a file from the ftp server
public boolean download(String base, String path, String file) {
this._working = true;
boolean outcome = true;
//create directory if not exists
File pathDir = new File(base + path);
if (!pathDir.exists()) {
pathDir.mkdirs();
}
//download file
try {
OutputStream output = new FileOutputStream(base + path + file);
this._ftp.retrieveFile(file, output);
output.close();
} catch (Exception e) {
outcome = false;
} finally {
this._working = false;
return outcome;
}
}
// Connect to the server
protected boolean _connect() {
try {
this._ftp.connect(this._host);
this._ftp.login(this._user, this._pass);
} catch (Exception e) {
return false;
}
return this._ftp.isConnected();
}
// Disconnect from the server
protected void _disconnect() {
try {
this._ftp.disconnect();
} catch (Exception e) { /* do nothing */ }
}
}
我希望能够在工作人员可用时为队列中的每个任务调用Worker.download(...),而不必为每次下载创建与 ftp 服务器的新连接。
任何帮助将不胜感激,因为我以前从未使用过线程,而我现在正在兜圈子。
【问题讨论】:
-
为什么没有连接池?这样,工作人员就不会链接到连接,他们从池中检查连接并使用它们返回它们。这是使用稀缺外部资源进行编程的常用方法,因为工作人员在整个期间不需要连接,您可以拥有比连接更多的工作人员......
-
也许你想使用Java's ExecutorService
-
@BoristheSpider 您应该根据您的评论做出回答。我认为OP必须结合ThreadPool和ConnectionPool的概念。
-
@Matt 请记住这是 Java。请使用 java 命名约定 - 无需以下划线开头。
标签: java multithreading ftp threadpool threadpoolexecutor