By implementing the Runnable interface the thread creation is the easiest way. You can construct a thread on any type of object that implements Runnable. To implement Runnable interface, a new class need only to implement run() method. When you implement the Runnable interface then create an instance of Thread from within that class. The Thread class has several constructor.

public Thread ()

public Thread(String thread_Name)

public Thread(Runnable threadObj)

public Thread(Runnable threadObj, String thread_Name)

public Thread(ThreadGroup groupObj, Runnable threadObj)

public Thread(ThreadGroup groupObj, Runnable threadObj, String name)

After the new thread is created, the start( ) method has to be used to start running, otherwise it will not be started. In essence, start( ) executes a call to run( ).

Example:

class NewThreadDemo implements Runnable

{

Thread t;

NewThreadDemo()

{

t=new Thread(this, "User Define Thread");

System.out.println("New userdefined child thread created" + this);

t.start();

}

public void run ()

{

try

{

for(int i = 1; i <=10; i++)

{

System.out.println("UserDefined Child Thread: " + i);

Thread.sleep(500);

}

}

(InterruptedException e)

{

System.out.println("UseDefine Child interrupted.");

}

System.out.println("Exiting UserDeinfed child thread.");

}

}

class ThreadDemo

{

public static void main(String args[])

{

new NewThreadDemo();

try

{

for(int i = 1; i <10; i++)

{

System.out.println("Main Thread: " + i);

Thread.sleep(500);

}

}

catch (InterruptedException e)

{

System.out.println("Main thread interrupted.");

}

System.out.println("Main thread exiting.");

}

}

Output:

The program was run three times, and all time different output was generated.