2

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.

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. but I want to be sure that WebReader class has read the data first and then carry on what should I do for that?

Vahid Hashemi
  • 5,182
  • 10
  • 58
  • 88
  • You can let the WebReader thread inform the UI when it is ready (a callback). See also http://stackoverflow.com/questions/1476170/how-to-implement-callbacks-in-java – The Nail Jan 01 '12 at 20:32

2 Answers2

6

SwingWorker is a built-in mechanism for executing long running tasks on a background thread so the EDT is not blocked. 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...? If not this answer won't apply.

Community
  • 1
  • 1
Jason Braucht
  • 2,358
  • 19
  • 31
  • +1 for the Swing Worker. The Swing tutorial on [Concurreny](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html) explains more about the EDT and has examples. – camickr Jan 01 '12 at 20:38
1

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. 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. When you use the notification mechanism to the user, it will have a means of waking up when the data arrives.

Francis Upton IV
  • 19,322
  • 3
  • 53
  • 57