Saiyine
Punto Com

Running background code in Java with Runnable

2007-07-05 02:46:04

Within Java, there are three main ways you can execute background threads: to inherit from the Thread class, to implement the Runnable interface and the TimerTask object.

This second example shows the second way, which is implementing the Runnable interface, that is almost identical to inheriting from Thread. What's its use, then? Easy, Java doesn't support multiple inheritance, so if we only had the Thread way we would be stuck without being able of accessing others classes in this way. So here comes implementing the Runnable interface, wich allows us inheriting from wichever class we want AND running the class in the background if we want to.

The code is fairly easy, and very similar to the Thread's. See that we use implementand not extends when declaring the class.

public class ThreadSample implements Runnable
{
    public void run()
    {
        for (int i = 0; i < 5000 ; i++)
            System.out.println(i + " " + Thread.currentThread().getName());
        System.out.println("End of thread " + Thread.currentThread().getName());
    }
    public static void main (String [] args) {
        new Thread ( new ThreadSample() , "+").start();
        new Thread ( new ThreadSample() , "-").start();
        new Thread ( new ThreadSample() , ":").start();
        new Thread ( new ThreadSample() , "*").start();
    }
}

Rollos antiguos

2007-07-05 02:33:01 - Ejecutar en segundo plano usando hilos (runnable).

2007-07-05 02:09:11 - Malas noticias.

2007-07-03 03:22:42 - Running background code in Java with Threads.

2007-07-03 03:16:44 - Ejecutar en segundo plano usando hilos (threads).

2007-07-03 03:03:54 - Kingdom come.

Saiyine

Selfie of meHi! Welcome to Saiyine Punto Com where I talk about anything that goes through my mind!

Puedo prometer y prometo que a la mayor brevedad aquí irá un menú o algo asín.