Java Thread - I want to generate numbers in order, for example: 1,2,3,4 & hellip; And so on (there will be only 2 threads only)

advertisements

Java Thread - i want to generate numbers in sequence eg: 1,2,3,4... (there will be 2 threads only ) 1st thread o/p will be 1 ,second thread o/p will be 2 , again 1st thread o/p will be 3 and so on , it can be upto 10 or upto n number whatever just wanna get the logic please help me guys :|

below is my attempt to do it but its not working i know there would be wait() and notify() methods for sure but cant figure out the proper way to use them !

class NumberGenerator { static int number = 0;

synchronized public int numGenerator()
{
    for(int i=0;i<20;i++)
    {
        System.out.println(i);
        number=i;
    }
    return number;
}

}

class FirstThreadClass extends Thread { NumberGenerator num;

FirstThreadClass(NumberGenerator num)
{
    this.num = num;
}

public void run()
{
    System.out.println("i am from 1st thread :"+num.numGenerator());

}

}

class SecondThreadClass extends Thread { NumberGenerator num;

SecondThreadClass(NumberGenerator num)
{
    this.num = num;
}

public void run()
{
    System.out.println("i am from 2nd thread :"+num.numGenerator());
}

}

public class ThreadTesting { public static void main(String[] args) {

    FirstThreadClass ftc = new FirstThreadClass(new NumberGenerator());
    SecondThreadClass stc = new SecondThreadClass(new NumberGenerator());
    ftc.start();
    stc.start();
}

}


    class NumberGenerator
    {
        static int counter = 0;

        public synchronized int getNextNumber()
        {
            return counter++;
        }

    }
    class FirstThreadClass
        extends Thread
    {
        NumberGenerator num;

        FirstThreadClass(NumberGenerator num)
        {
            this.num = num;
        }

        public void run()
        {
            System.out.println("i am from 1st thread :" + num.getNextNumber());

        }

    }
    class SecondThreadClass
        extends Thread
    {
        NumberGenerator num;

        SecondThreadClass(NumberGenerator num)
        {
            this.num = num;
        }

        public void run()
        {
            System.out.println("i am from 2nd thread :" + num.getNextNumber());
        }

    }

    public class ThreadTesting
    {
        public static void main(String[] args)
        {
            FirstThreadClass ftc = new FirstThreadClass(new NumberGenerator());
            SecondThreadClass stc = new SecondThreadClass(new NumberGenerator());
            for (int k = 0; k < 10; k++)
            {
                ftc.run();
                stc.run();
            }
        }

    }