我有一个应用程序,它将我的System.out文本重定向到Jtextarea。这很好用,但是当我调用应用程序中的一个方法时,它会创建多个线程,并使用一个闩锁计数器来等待它们完成。然后,该方法调用latch.await(),以便在其他线程完成之前不会完成代码的运行。问题是,一旦调用了latch.await()代码,我的JtextArea就会停止发布文本,直到所有线程都完成。对此有什么想法吗?Eclipse控制台能够在latch.await()运行时保持posting,所以这必须是可能的。
示例:从GUI执行以下操作:
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("You pressed Start");
MyGoogleSearch startParsing = new MyGoogleSearch();
try {
startParsing.startParser(othoSelection); ...MyGoogleSearch:
Enumeration e = hm.elements();
//Read in src/Ontology/Ontology.txt
//Put each line into the searchQuery ArrayQueue
while ((strLine = br.readLine()) != null)
{
searchQuery.put(strLine);
}
System.out.println("Finsihed loading");
//Create 32 threads (More threads allows you to pull data from Bing faster. Any more than 32 and Bing errors out (you start to pull data
//too fast)
for(int i = 0; i < 32; i++)
{
System.out.println("Starting thread: " + i);
new NewThread();
}
//Wait for all of the threads to finish
latch.await();
e = hm.keys();
//Write the URL's from the hashmap to a file
while (e.hasMoreElements())
{
out.write(e.nextElement() + "\n");
}
//close input/output stream
in.close();
out.close();
System.out.println("Done");然后线程会做一些事情
MyGoogleSearch.latch.countDown();发布于 2011-12-10 03:00:34
这工作得很好,但是当我调用应用程序中的一个方法时,它会创建多个线程,并使用一个锁存计数器来等待它们完成。
您可以通过在单独的线程中调用该方法来解决此问题。但是,我怀疑该方法正在等待所有线程完成,因为它希望聚合一些结果,然后返回聚合的结果(或类似的结果)。如果是这种情况,那么有几种方法可以处理它,但对于图形应用程序来说,最有意义的方法可能是让线程使用从该方法获得的任何结果调用回调。
如果你发布一些示例代码,我们可以为你提供更具体的答案和如何做到这一点的例子。
更新:
我很难读懂你的代码,但我认为'startParser‘是被阻塞的调用。此外,UI似乎不需要等待结果,所以我建议您尽可能执行最简单的操作:
MyGoogleSearch startParsing = new MyGoogleSearch();
Thread t = new Thread(new Runnable(){
public void run(){
startParsing.startParser(othoSelection);
}
}
// don't wait for this thread to finish
t.start();https://stackoverflow.com/questions/8450154
复制相似问题