我已经实现了一种将FTP文件从服务器计算机传输到客户端的应用程序
for(String sourceFolder : foldersPaths){
transferFolder(channelSftp,SFTPWORKINGDIR+sourceFolder,
DESWORKINGDIR+sourceFolder.replace("/","\\"));
}
这段代码遍历字符串的ArrayList,其中包含我需要传输的每个文件的源路径。我当时正在考虑利用带宽并同时针对不同的文件启动多个传输。
如何创建同时执行“ transferFolder”方法的不同线程。是否可以确保同一项目不会在不同线程中循环两次,这是否安全?
谢谢
最佳答案
Set<String> submitted = Collections.synchronizedSet(new HashSet<String>());
ExecutorService executorService = Executors.newFixedThreadPool(10); // how many threads to work with it
for(final String sourceFolder : foldersPaths){
if(! submitted.contains(sourceFolder)) {
Runnable runnable = new Runnable() {
@Override
public void run() {
transferFolder(...); // your method invoked here
}
};
if (submitted.add(sourceFolder)) {
executorService.submit(runnable);
}
}
}
executorService.shutdown();