Re: threads and GUIs
LC's No-Spam Newsreading account wrote:
In both cases I get a java.lang.IllegalThreadStateException on the
tsw4.start(); statement in the monitor() constructor
but what is the state of the thread ?
(and why is it illegal ?)
Probably because you have already called start() on that thread.
Threads can only be started once.
It sounds to me like you still have some concurrency problems.
Note that monitor() does no graphics of its own. I tried also with a
monitor() method, and to call it in various places, but with obviously
The problem is that Monitor is a JPanel, which has some implications of
it's own, i.e., it still needs to be thread safe. Quoting you from some
stuff earlier in your post:
> monitor() at some point does a tsw4.start();
> where tsw4 is a static Thread tsw4 = new Thread(sw4);
> and sw4 is an instance of a class which handles the http
> connection. All this defined once forever in the prologue (global
> to my topmost class)
>
This strikes me as a problem. If sw4 truly is an instance, then you are
almost certainly going to have threading problems. I would make a new
sw4 instance each time you use it:
SW4 sw4 = new SW4();
new Thread( sw4 ).start();
Not bomb proof, but still more likely to be correct and more robust in
the long term.
On a more fundamental level, I think you should be using a SwingWorker.
This class makes it much easier to write thread safe Swing programs.
It handles the threading for you so you don't have to. Give your
Monitor class a "setResult( Object )" method (which does not have to be
thread safe) and do something like this:
public class HttpTask extends SwingWorker<Void, Object> {
@Override
public Void doInBackground() {
SW4 sw4 = new SW4();
sw4.run();
return null;
}
@Override
protected void done() {
try {
monitor.setResult(get());
} catch (Exception ignore) {
}
}
}
Now you can call this from anywhere, and it'll be safe(r):
(new HttpTask()).execute();
<http://java.sun.com/docs/books/tutorial/uiswing/concurrency/worker.html>
You also should lay off Thread.sleep(int), which will block the calling
thread. This is really bad for Swing. Use a Swing Timer instead to do
your timing tasks.
<http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html>