我正在創建一個Java應用程序。在啓動時,我的應用程序將下載所有必需的文件。我的應用程序將解析XML文件並從XML文件的URL中下載文件。我希望我的應用程序下載文件「一步一步」,所以我使用FutureTask
我的問題是,FutureTask
不適用於我的應用程序。Java - FutureTask不工作?
這是我的代碼的一部分。
Startup.class
public void startDownloading()
{
Thread t = new Thread(new Runnable()
{
public void run()
{
downloader.startDownload();
}
});
t.run();
}
}
Downloader.class
private LibrariesDownloader ld;
private RDownloader rd;
public Downloader()
{
this.ld = new LibrariesDownloader(launcher);
this.rd = new RDownloader(launcher);
}
public void startDownload()
{
ExecutorService executor = Executors.newFixedThreadPool(2);
FutureTask<Void> libDownloader = new FutureTask<Void>(ld);
FutureTask<Void> resDownloader = new FutureTask<Void>(rd);
executor.execute(libDownloader);
if(libDownloader.isDone())
{
executor.execute(resDownloader);
}
}
LibrariesDownloader.class(& RDownloader.class(代碼幾乎相同,唯一的URL是不同的))
public class LibrariesDownloader implements Callable<Void>
{
private Proxy proxy = Proxy.NO_PROXY;
@Override
public Void call() throws Exception
{
try
{
URL resourceUrl = new URL("http://www.exmaple.com/libraries.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(resourceUrl.openConnection(proxy).getInputStream());
NodeList nodeLst = doc.getElementsByTagName("Content");
for (int i = 0; i < nodeLst.getLength(); i++)
{
Node node = nodeLst.item(i);
if (node.getNodeType() == 1)
{
Element element = (Element)node;
String key = element.getElementsByTagName("Key").item(0).getChildNodes().item(0).getNodeValue();
final File path = new File("C://test/", key);
final String url = "http://www.exmaple.com/dl/" + key;
final String fileName = key;
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>()
{
@Override
protected Void doInBackground() throws Exception
{
try
{
URL fileURL = new URL(url);
org.apache.commons.io.FileUtils.copyURLToFile(fileURL, path);
}
catch(Exception e)
{
URL redownloadURL = new URL("http://www.example.com/dl/" + fileName);
File p = new File("C://test/", fileName);
org.apache.commons.io.FileUtils.copyURLToFile(redownloadURL, p);
}
return null;
}
@Override
public void done()
{
System.out.println(fileName + " had downloaded successfully");
}
};
worker.execute();
}
}
}
catch(Exception e)
{
launcher.println("An error was found when trying to download libraries file " + e);
}
return null;
}
}
我的XML文件中有大量的<Key></Key>
。我的應用程序可以執行LibrariesDownloader
並下載所有庫文件。所有庫文件下載後,我的應用程序就停在那裏。它不會執行RDownloader
。
是我的應用程序中的任何代碼錯誤?感謝您的幫助。
定義 「不工作」。此外,您應該閱讀Thread.run(),Thread.start()和FutureTask.isDone()的javadoc。目前還不清楚,只是從代碼中,你正在嘗試做什麼。 –
我想在LibrariesDownloader.class下載文件後,RDownloader會啓動並下載「R」文件 – Jeremy
所以你需要順序執行而不是並行執行。爲什麼使用線程呢?正如我所說的,閱讀isDone()的javadoc。這不是一種阻止方法。 get()是一種阻塞方法。 –