Saturday 12 October 2013

Program to print /*/*/* .... using Threads

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

    public void run() //throws Exception
    {
        for(int i=1;i<=n;i++)
        {
            if (i%2!=0)
            {
                System.out.print("/");   
            }
            else
            {           
                try{
                Thread.sleep(250);
                }
                catch(InterruptedException e){}
            }
        }
    }
}

class Star implements Runnable
{
    int n;
    Star(int n)
    {
        this.n=n;
    }

    public void run()
    {
        for(int i=1;i<=n;i++)
        {
            if (i%2==0)
            {
                System.out.print("*");   
            }
            else
            {
                try{
                Thread.sleep(200);
                }
                catch(InterruptedException e){}
               
            }
        }
    }
}

class PatternThreads
{
    public static void main(String ahlam[])
    {
        int n;
        Scanner d=new Scanner(System.in);
        System.out.println("Enter the number");
        n=d.nextInt();
        Slash sh=new Slash(n);
        Star st=new Star(n);
        Thread th=new Thread(st);
        sh.start();
        th.start();
    }
}

/*
Output

C:\Users\Ahlam\Google Drive\My Lectures\Fall\OOPM\Programs>javac PatternThreads.java

C:\Users\Ahlam\Google Drive\My Lectures\Fall\OOPM\Programs>java PatternThreads
Enter the number
5
/*/*/
C:\Users\Ahlam\Google Drive\My Lectures\Fall\OOPM\Programs>
*/

No comments:

Post a Comment