让Gui Console忽略latch.await()

时间:2011-12-09 18:42:38

标签: java multithreading user-interface

我有一个将我的System.out文本重定向到Jtextarea的应用程序。这工作正常,但当我调用我的应用程序中的一个方法是创建多个线程并使用锁存计数器等待它们完成。然后该方法调用latch.await(),以便在其他线程完成之前它不会完成其代码的运行。问题是,一旦调用了latch.await()代码,我的JtextArea会停止发布文本,直到所有线程都完成。围绕这个想法吗?当latch.await()运行时,Eclipse控制台能够保持发布,因此必须可以。

实施例: 从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();

1 个答案:

答案 0 :(得分:0)

  

这很好但是当我调用我的应用程序中的一个方法时,会创建多个线程并使用一个锁存计数器来等待它们完成。

你可以通过在一个单独的线程中调用该方法来解决这个问题。但是,我怀疑该方法正在等待所有线程完成,因为它想要聚合一些结果然后返回聚合结果(或类似的东西)。如果是这种情况,那么有几种方法可以处理它,但可能对图形应用程序最有意义的方法是让线程调用带有从该方法获得的任何结果的回调。

如果您发布了一些示例代码,那么我们可以为您提供更具体的答案以及如何操作的示例。

更新

我很难读你的代码,但我认为'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();
相关问题