How to start a thread?

To start a thread we have to call the start()
t.start();
Extending Thread:
class demo extends Thread
{
public void run(){System.out.println("this is run");}
public static void main(String[] args){
demo d=new demo();
d.start();
}};
Implementing Runnable:
class demo implements Runnable
{
public void run(){System.out.println("this is run");}
public static void main(String[] args){
demo d=new demo();
Thread t=new Thread(d);
t.start();
}};
So what happens after you call start()?
■ A new thread of execution starts (with a new call stack).
■ The thread moves from the new state to the runnable state.
■ When the thread gets a chance to execute, its target run() method will run.

No comments:

Post a Comment