简体   繁体   English

如何使我的程序等待特定的线程,又不影响GUI的交互性?

[英]how to make my program to wait for a particular thread and also not affecting my GUI's interactivity?

I have a program based on MVC which gets data from internet and start to parsing it and of course in networking programs we need to have threads. 我有一个基于MVC的程序,该程序从Internet获取数据并开始解析它,当然在网络程序中我们需要有线程。

I have a class for reading data from internet such below : 我有一堂课,用于从互联网读取数据,如下所示:

public class WebReader extends Thread
{


    private String result="";



    public String getResult()
    {
        return result;
    }
    public void setResult(String t)
    {
        result = t;
    }

    public WebReader(get args here)
    {
        //initializing 
    }

    public void getData()
    {
        //call the big getData(args);

    }
    public void getData(Sargs)
    {
        //magics happens here
    }

    @Override
    public void run() 
    {

        //call getData()
    }
}

and for using this class inside my model I've been using below code : 对于在我的模型中使用此类,我一直在使用以下代码:

//inside a function
WebReader wr = new  WebReader(args);
        wr.start();
            wr.join();
            String s = wr.getResult();
            this.parseData(s);

I know by using join() I'm join the thread to the current thread and by doing this my GUI will stuck till complete result come from network. 我知道通过使用join()将线程连接到当前线程,并且这样做,我的GUI会一直停留到完整的结果来自网络。 but I want to be sure that WebReader class has read the data first and then carry on what should I do for that? 但是我想确保WebReader类先读取数据,然后继续执行该操作?

SwingWorker is a built-in mechanism for executing long running tasks on a background thread so the EDT is not blocked. SwingWorker是一种内置机制,用于在后台线程上执行长时间运行的任务,因此不会阻止EDT。 Depending on the overall design and intent of your application, you may find it easier than some of the alternative solutions. 根据整体设计和应用程序的意图,您可能会发现它比某些替代解决方案更容易。

Edit: I'm assuming your GUI is in Swing...? 编辑:我假设您的GUI在Swing中...? If not this answer won't apply. 如果不是,此答案将不适用。

Without giving you the exact solution, I can give you some things to consider. 在没有给您确切解决方案的情况下,我可以考虑一些事项。 You will need to do something in the GUI to indicate the user should wait. 您将需要在GUI中执行某些操作以指示用户应等待。 This could be as little as a wait/busy cursor, or some sort of progress monitor. 它可能只有等待/忙碌光标或某种进度监视器。 Implementing these is different depending on the GUI technology that you are using. 根据所使用的GUI技术,实现这些方法的方法有所不同。 When you use the notification mechanism to the user, it will have a means of waking up when the data arrives. 当您向用户使用通知机制时,它将有一种在数据到达时唤醒的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM