Java Program on How to Create User define Thread

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

Program 1

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

Program 2

{
    public static void main(String args[]) throws InterruptedException
  {
            int i;
             System.out.println("Main Thread Starts");
             MyThread M1=new MyThread();
            M1.start();
            for(i=1;i<=10;i++)
            {
  System.out.println("Main : " + i);
                 Thread.sleep(500); 
            }
         System.out.println("Main Thread Ends Here");
   }
}

Program 3

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 4

package dataflair;

public class TestMainThread 
{
    public static void main(String[] args) throws InterruptedException
    {
            MyThread M1=new MyThread();  // Create of thread
            MyThread M2=new MyThread(); 
            MyThread M3=new MyThread(); 
            
            M1.setName("First Thread:");
            M2.setName("Second Thread:");
            M2.setName("Third Thread:");
            
            M1.start();// Thread move into runnable mode
            M2.start();
            M3.start();
            
//            System.out.println("Main Thread Starts");
//            for (int i = 100; i < 110; i++) 
//            {
//                System.out.println("Main: " + i); 
//                Thread.sleep(1000);
//            }
    }
    
}

 

Your opinion matters
Please write your valuable feedback about DataFlair on Google

follow dataflair on YouTube

Leave a Reply

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