Running background code in Java with Threads
2007-07-03 03:22:42
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 first example shows how to use the inheritance of the Thread class. Copy-paste it into your editor of choice and check how easy is to create alternative threads to your program main's. Look how the threads concurrency makes the threads output get mixed at the console: probably it'll become more aparent by increasing the top of the for.
public class ThreadEjemplo extends Thread{
public ThreadEjemplo(String str)
{
super(str);
}
public void run()
{
for (int i = 0; i < 100 ; i++)
System.out.println(getName());
System.out.println("Fin " + getName());
}
public static void main (String [] args)
{
new ThreadEjemplo("A").start();
new ThreadEjemplo("B").start();
new ThreadEjemplo("C").start();
new ThreadEjemplo("D").start();
}
}