Saturday, 12 October 2013

Program to demonstrate Thread using Thread Class

//Program to demonstrate Thread using Thread Class
//Developed by Ahlam Ansari
import java.util.*;
   
class Thread1 extends Thread
{
    int n;
    Thread1 (int n)
    {
        this.n=n;
    }

    public void run()
    {
        for(int i=1;i<=n;i++)
        {
            System.out.println("Thread 1");   
        }
    }
}

class Thread2 extends Thread
{
    int n;
    Thread2 (int n)
    {
        this.n=n;
    }

    public void run()
    {
        for(int i=1;i<=n;i++)
        {
            System.out.println("Thread 2");   
        }
    }
}

class ExtendsThread
{
    public static void main(String ahlam[])
    {
        int n;
        Scanner d=new Scanner(System.in);
        System.out.println("Enter the number");
        n=d.nextInt();
        Thread1 th1=new Thread1(n);
        Thread2 th2=new Thread2 (n);
        th1.start();
        th2.start();
    }
}

/*
Output
C:\Users\Ahlam\Google Drive\My Lectures\Fall\OOPM\Programs>javac ExtendsThread.java

C:\Users\Ahlam\Google Drive\My Lectures\Fall\OOPM\Programs>java ExtendsThread
Enter the number
5
Thread 2
Thread 2
Thread 2
Thread 2
Thread 2
Thread 1
Thread 1
Thread 1
Thread 1
Thread 1

C:\Users\Ahlam\Google Drive\My Lectures\Fall\OOPM\Programs>java ExtendsThread
Enter the number
5
Thread 1
Thread 1
Thread 1
Thread 1
Thread 1
Thread 2
Thread 2
Thread 2
Thread 2
Thread 2

C:\Users\Ahlam\Google Drive\My Lectures\Fall\OOPM\Programs>
*/

No comments:

Post a Comment