Tuesday, August 10, 2010

Java's Thread Class

 A thread is a flow of execution from start to end and with multi-tasking in most computer systems, several programs can be run almost at the same time (with milliseconds interval among programs).

A process may create several threads and in Java, a singe tread from a simple program is actually done. However, we can also create several threads to maximize our processor. And, Java allows thread creation through extending the Thread class or running a Runnable interface.

When using Thread class, you can execute the overriding run method  through start( ) method. See the sample program below that displays 5 times a message Hello.

[+/-] show/hide

class HelloThread1 extends Thread {
private static final int TIMES =5;
public void run()
for(int x=1;x<=TIMES;x++) System.out.println("Hello"); } } class HelloThread2{ public static void main(String[] args){ HelloThread1 myHello=new HelloThread1(); HelloThread1 Hello = new HelloThread1(); Hello.start(); myHello.start(); } }

No comments: