【问题标题】:Get Gui Console to ignore latch.await()获取 Gui 控制台以忽略latch.await()
【发布时间】:2011-12-09 18:42:38
【问题描述】:

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

示例: 从图形用户界面:

btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("You pressed Start");
MyGoogleSearch startParsing = new MyGoogleSearch();
try {
startParsing.startParser(othoSelection); ...

我的谷歌搜索:

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();

【问题讨论】:

    标签: java multithreading user-interface


    【解决方案1】:

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

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

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

    更新:

    我很难阅读您的代码,但我认为“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();
    

    【讨论】:

    • 用一个例子更新了我的答案......虽然你的代码看起来有点混乱,因为你的代码显示了一个方法体,但我不知道它是startParser方法还是其他方法。
    • 这为我解决了。 startParser 是我的示例代码中显示的方法。试图在不发布几百行代码的情况下获得足够的示例:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多