Full width home advertisement

Post Page Advertisement [Top]

Java Thread and Runnable

Runnable (java.lang.Runnable): Runnable is basically a interface which is used to create a task(runnable code) which can run in Thread. Before reading Runnable you must learn Thread first.

Runnable define a method run() which must override
when runnable implements in class.
When thread start, the run() method run in seprate thread.

Example 1:

class RunnableTest implements Runnable
{
public void run()
{
System.out.println("Runnable object called.");
}

public static void main(String args[])
{
RunnableTest r=new RunnableTest();
Thread t=new Thread(r);
t.start();
}
}

Example 2:

class RunnableTest
{
public static void main(String args[])
{
Runnable r=new Runnable(){
public void run()
{
System.out.println("Runnable object called");
}
};
Thread t=new Thread(r);
t.start();
}
}

Tip:
You may replace:

Thread t=new Thread(r);
t.start();

with:

new Thread(r).start();

No comments:

Post a Comment

Bottom Ad [Post Page]

| Designed by Colorlib