
Signature
Eric Sosman
esosman@acm-dot-org.invalid
> What is supposed to happen when the scanner thread finishes its scan?
Once the scanner thread is over a new frame is opened, with the results of
the scan.
Anyway, if I don't call the join() method on the main thread or if I don't
make a while loop until the scanner thread is over the scanning process
stops immediately, often without reporting any result.
The actual code is something like this:
// The main class:
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand() == "Scan" ) {
Thread t = new Scan();
t.start();
try {
t.join();
}
catch (InterruptedException e) {}
// Or: while (t.isAlive()) Thread.yield();
// And this is the method run() in the "Scan" class:
public void run() {
curPos=0;
int ports[] = new int[PORT_NUM];
for (int i=0; i<PORT_NUM; i++) {
try {
Socket s = new Socket(host_name,i);
if (!s.isClosed()) {
ports[curPos]=i;
curPos++;
}
}
catch (IOException e) {}
........
And then it prints the results of the scan (the open ports now stored in
the array "ports") in a JTable or something like that. But using join() or
yield() causes the main frame to "freeze" until the scanner thread is
over, and I just wanted to know if there's a way to keep it alive while
the scan is in progress...thanks for the help.

Signature
questo articolo e` stato inviato via web dal servizio gratuito
http://www.newsland.it/news segnala gli abusi ad abuse@newsland.it
Matt Humphrey - 26 Jun 2006 13:01 GMT
>> What is supposed to happen when the scanner thread finishes its scan?
>
[quoted text clipped - 16 lines]
> t.join();
> }
^^^ You are launching a separate thread from the EDT and then promptly
making the EDT wait until that thread is finished--that's the same as not
using a thread at all. By making the EDT wait the UI will appear to freeze
and results will not display until the entire thread finishes.
> catch (InterruptedException e) {}
>
[quoted text clipped - 24 lines]
> over, and I just wanted to know if there's a way to keep it alive while
> the scan is in progress...thanks for the help.
First, drop the join. Second, when you have results in your run method, do
the following to make the EDT display them. UI objects (Swing) should only
be manipulated from the EDT--except for one or two they're not threadsafe.
This technique allows non-EDT threads to request UI changes in a thread-safe
way.
SwingUtilities.invokeLater (new Runnable () {
public void run () {
// Whatever code you had above to display your results should go here.
// It will be executed in the EDT thread which will preserve thread
safety.
// You can use a similar technique to display partial results and status
// information--you don't have to wait for your Scan thread to finish.
}
});
Cheers,
Matt Humphrey matth@ivizNOSPAM.com http://www.iviz.com/