我想第一次使用java期貨。我有一個課程設置爲解壓縮一些文件。想要遞歸解壓縮,因爲我有zip文件包含zip文件。使用Java期貨的線程安全集合操作
我有一個驅動器類,實例化一個實現可調用的Uncompressor類。解壓縮器開始解壓縮,如果遇到另一個.zip,它會創建一個自己的實例,將其添加到池中,然後繼續。
僞代碼
From DriverClass:
.
.
.
ExecutorService pool = new Executors.newFixedThreadPool(4);
Uncompressor uc = new Uncompressor(pool, compressedFile);
Collection<File> files = uc.uncompress();
for(Future <Collection<File>> f : uc.futures)
files.addAll(f.get());
// at the end of this loop, files doesnt seem to hold all of my files
這裏是我的uncompressor類
public class Uncompressor implements Callable<Collection<File>>
{
public Set<Future<Collection<File>>> futures = new HashSet<Future<Collection<File>>>();
File compressedFile;
public Uncompressor(ExecutorService pool, File compressedFile)
{
this.pool = pool;
this.compressedFile = compressedFile;
}
public Collection<File> call() throws Exception[
return uncompress();
}
public Collection<File> uncompress()
{
List<File> uncompressedFiles = new ArrayList<File>();
.
.Loop
.//Try to uncompress the file. If the archive entry is a zip file, do the following:
Callable<Collection<File>> callable = new Uncompressor(this.pool, archiveFileEntry);
Future f = pool.submit(callable);
futures.add(f);
//else, add files to a collection here for returning
uncompressedFiles.add(archiveFileEntry);
.EndLoop
return uncompressedFiles;
.
.
}
所以,問題是我DriverClass,我的文件的採集應保存所有未壓縮的文件從遞歸在這裏下潛似乎並沒有包含所有的文件。我認爲我在從未來獲取返回值時做錯了什麼。是否因爲我定義了一個類成員變量futures
?
謝謝
是的,這是可能的。它可以是zip內的任意數量的zip,真的是 – Derek 2012-04-20 15:08:09