Java Program on Thread Class Methods

Free Java courses with 37 real-time projects - Learn Java

Program 1

package dataflair;

public class MyThread1 extends Thread
{
    public void run()
    {     int i;
        try 
        {
            System.out.println(getName()+" Starts: ");
            for (i = 1; i <= 10; i++) 
            {
                System.out.println(getName() + " : "+i);    
                Thread.sleep(1000);
            }
        } 
        catch (InterruptedException e) 
        {
             System.out.println(e);            
        }
           System.out.println(getName()+" End: ");
    }
}

Program 2

package dataflair;


public class MyThread2 extends Thread
{
     public void run()
    {     int i;
        try 
        {
            System.out.println(getName()+" Starts: ");
            for (i = 500; i <= 510; i++) 
            {
                System.out.println(getName() + " : "+i);    
                Thread.sleep(1000);
            }
        } 
        catch (InterruptedException e) 
        {
             System.out.println(e);            
        }
        System.out.println(getName()+" End: ");
    }
}

Program 3

package dataflair;


public class TestMain 
{
    public static void main(String[] args) throws InterruptedException
    {
           System.out.println("Main Thread Starts: ");    
           MyThread1 M1=new MyThread1();
           MyThread2 M2=new MyThread2();
//           System.out.println(M1.getName());
//           System.out.println(M2.getName());
           M1.setName("First : ");
           M2.setName("Second : ");
           M1.start();
           M2.start();
           System.out.println(M1.isAlive());  //true
           System.out.println(M2.isAlive()); //true
           M1.stop();
           //M1.join();
           //M2.join();
           System.out.println(M1.isAlive());  //false
           System.out.println(M2.isAlive());//false
           
           System.out.println("Main Thread End Here: ");    
    }
    
}

 

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *