22.07.2013 Views

PDF de la clase 34

PDF de la clase 34

PDF de la clase 34

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Ejemplo <strong>de</strong> Runnable<br />

Por ejemplo, consi<strong>de</strong>re <strong>la</strong> c<strong>la</strong>seFrameInThread <strong>de</strong>finida como<br />

public c<strong>la</strong>ss FrameInThread<br />

extends Frame implements Runnable {<br />

// los constructores y otros métodos van aquí<br />

public void run() {<br />

}<br />

// el código ejecutado en el hilo va aquí<br />

}<br />

Si quisiéramos que una instancia <strong>de</strong> <strong>la</strong> c<strong>la</strong>seFrameInThread se<br />

ejecutase en su propio hilo, podríamos utilizar <strong>la</strong> sentencia<br />

Thread t = new Thread(new FrameInThread() );<br />

Iniciar y <strong>de</strong>tener hilos<br />

• ¿Cómo se inicia un hilo?: L<strong>la</strong>me astart()<br />

en <strong>la</strong> instancia <strong>de</strong>l hilo.<br />

Thread t = new MyThread();<br />

t.start();<br />

• ¿Cómo se <strong>de</strong>tiene un hilo y se <strong>de</strong>struye?: Deje<br />

que termine el método run() y que <strong>la</strong> referencia<br />

<strong>de</strong>l hilo finalice o establezca <strong>la</strong> referencia en null.<br />

El recolector <strong>de</strong> basura rec<strong>la</strong>mará el<br />

almacenamiento <strong>de</strong>l hilo.<br />

t.stop() se <strong>de</strong>spreciará.<br />

11<br />

12<br />

6

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!