| Chris Smith 2004-09-21, 4:02 am |
| Ben Hoffmann wrote:
> I have an application that downloads a series of items from a web site -
> with J2SE. I want to implement a cancel function. I'm gathering this
> means I need to use threads in order to interupt the download - is this
> correct or am I complicating this?
In theory, there are two possibilities here: use multiple threads, or
use asynchronous (non-blocking) I/O functions. However, because you are
using a graphical user interface, you are required to perform blocking
operations outside of the event dispatch thread. That means that
although you still have the choice of blocking or non-blocking I/O, you
will need to create a new thread in either case.
> If threads are the correct approach - is there a simple pattern or
> example that explains how to do this - without getting into J2EE or
> client - server complications - (beyond my expertise at this point)?
The basic idea behind it is as follows:
// in some accessible location:
Thread t;
// in an event handler:
t = new Thread(new Runnable() {
public void run()
{
try
{
// code to read from socket
}
catch (InterruptedIOException e) { }
catch (IOException e)
{
handleException(e);
}
}
});
t.start();
And later, to cancel:
t.interrupt();
--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
|