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();
}
}