All the 3 methods to make threads have been discussed. The main benefit of thread is it can run even if your method has completed its function. It can be useful in a number of situations like you want to perform 2 operation at similar time etc.
Threads actually run even if your main function has ended .It run independent of others.You are going to require threads in your day to day java programs.
Listing 1: Define Class and the main method
public class Threads
{
public static void main(String args[])
{
MainThread t=new MainThread();
t.start();
Thread t1=new Thread(new Runn());
t1.start();
Thread t2 = new Thread(){
public void run(){
System.out.println("Anonymous");
}
};
t2.start();
}
}
Here,
Now we define the MainThread class
Listing 2: MainThread class
class MainThread extends Thread
{
public void run()
{
System.out.println("Hi you reached MainThread");
}
}
Here,
Now we define the Runn class
Listing 3: Runn class
class Runn implements Runnable
{
public void run()
{
System.out.println("Runnable interface");
}
} Here,
Listing 4: Full Source code
class MainThread extends Thread
{
public void run()
{
System.out.println("Hi you reached MainThread");
}
}
class Runn implements Runnable
{
public void run()
{
System.out.println("Runnable interface");
}
}
public class Threads
{
public static void main(String args[])
{
MainThread t=new MainThread();
t.start();
Thread t1=new Thread(new Runn());
t1.start();
Thread t2 = new Thread(){
public void run(){
System.out.println("Anonymous");
}
};
t2.start();
}
}
Hi you reached MainThread
Runnable interface
Anonymous







See the prices for this post in Mr.Bool Credits System below: