Do Time Consuming Stuff in a New Thread
Did you ever notice that when you do too much time consuming work in the event
handler of a push button, your user interface becomes really draggy or comes to a
screeching halt?
To free the user interface, you can create a new thread in the event handler and
let it do the time consuming work after the event handler has returned.
This thread is a worker thread that does its job and then dies. You just get it
started and you never have to communicate with it or think about it again. So, it
doesn't even need a name. Clip out the thread creation/activation code from the
listing below and change the name getBusy to the name of the worker method that you
provide, and you've got the lightest-weight thread you can get. Your method must
return void and take no arguments.
One potential problem, is that the user might be able to push the button quicker
than your program can do the work. An easy way to prevent that kind of problem is
to make the button invisible (therefore unpushable) in the event handler, then to
make it visible again just before the new thread finishes and dies. I've
demonstrated how to handle hiding a button in Listing 1, but if you don't need it,
don't use it.
One other thing worth mentioning is the label "WhateverUWantToCallIt" -- you can
make it any symbol, or even the empty string ""; if you use several of these
anonymous threads, there isn't any requirement that they have different labels, but
you might find it useful to label them distinctively so that they are easy to find
in the editor, in case you need to work on them individually.
Any number of different anonymous threads can use the same method as their run
method, without causing any problems.
Naturally, you can't have different methods with the same name and the same
arguments, or the compiler will complain.
Both the creation of the new thread and the run method have to be in the same class.
Follow these easy requirements and you can have an elegant, smooth running user
interface.
Bill Spees
August, 2004
--------------------------- Listing 1--------------------------------
1 class Blahblah {
2 // methods and attributes go here
3
4 protected void someButtonPushOrSomething()
5 {
6 // yada
7 // yada
8 // almost ready to go back
9
10 new Thread("WhateverUWantToCallIt"){public void run() {getBusy();}}.start();
11 someButton.setVisible(false);
12
13 } // now the user interface is freed
14
15 // this is the run method of the new thread
16 protected void getBusy() { // here is where you do the bulk of the work that's
17 //done in response to the
18 // button push, without wasting time in the parent thread
19 // do a lot of work here.
20 // do still more work
21 // almost ready to go back
22 someButton.setVisible(true);
23 } // now the nameless new thread is dead.
24
25
26 //more methods and attributes, if desired
27
28 } // end of class Blahblah
|