Saturday, 12 October 2013

Program to demonstrate Thread using Runnable Interface

//Program to demonstrate Thread using Runnable Interface
//Developed by Ahlam Ansari
import java.util.*;
   
class Thread1  implements Runnable
{
    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  implements Runnable
{
    int n;
    Thread2 (int n)
    {
        this.n=n;
    }

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

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

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

C:\Users\Ahlam\Google Drive\My Lectures\Fall\OOPM\Programs>java ImplementsRunnable
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>java ImplementsRunnable
Enter the number
9
Thread 1
Thread 1
Thread 1
Thread 1
Thread 1
Thread 2
Thread 2
Thread 2
Thread 2
Thread 2
Thread 2
Thread 2
Thread 2
Thread 2
Thread 1
Thread 1
Thread 1
Thread 1

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

No comments:

Post a Comment