views:

131

answers:

3

I have one class DataThread inherited from Thread. I am using two DataThread objects ReadThread and WriteThread. I have another thread where Main_GUI is running.

Now when I press a button on main_GUI it calls a method x.method1() and then this method uses the WriteThread method WriteThread.sleepForReset(). In

public void sleepForReset(){
    try {
        sleep(28000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

When I press the button on main_GUI the GUI stalls for 28000 miliseconds. If I am calling sleep on WriteThread then why it halts the main_GUI? Is it because the sleep is a static method? If yes can anybody suggest how to sleep the WriteThread without affecting Main_GUI?

+1  A: 

I think calling people Geeks is not necessarily a good way to get help, but to answer your question, you're seeing the sleep because you're calling Thread.sleep on the event dispatch thread. Swing's GUI operations run on this single thread. If you need to do long running background work, you should delegate it to a SwingWorker.

Also, the handling of interrupted exception is not very robust. At the very least, you should be reinterrupting the thread with Thread.currentThread().interrupt().

Jeff Storey
Thanks for the suggestion.......I will never ever call anybody "Geek" in my life... But what I can do ? I am desperate for help... :)
Surjya Narayana Padhi
+5  A: 

If you are calling WriteThread.sleepForReset() from within your actionPerformed method, you are actually calling it from within the EventDispatch Thread. Even though you have an object that represents your WriteThread, calling a method on that object from within the EventDispatch Thread will cause the process to be performed within the EDT.

Take a look at this tutorial on using worker threads in Java. Note that it isnt enough to just have a class that inherits from Thread, you need to have the instances of these Threads to be started for you to have a multithreaded app. The tutorial provided will give you a good idea on one way to get started.

akf
A: 

Thanks all of you for suggesting me different options..... But I used TimeTask.schedule() and worked. I scheduled my job for later instead of using sleep in the current thread......

Surjya Narayana Padhi