Java Thread - i want to generate numbers in sequence eg: 1,2,3,4...so on (there will be 2 threads only )

4.4k views Asked by At

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();
}

}

5

There are 5 answers

0
coder On

you can achieve this using cyclic barrier, create a barrier and once two threads have generated one number each print the two numbers

class ThreadTest {

    private CyclicBarrier cyclicBarrier = new CyclicBarrier(2, new Runnable() {
        @Override
        public void run() {
            System.out.println(oddNumberGenerator.result);
            System.out.println(evenNumberGenerator.result);
        }
    });

    private NumberGenerator oddNumberGenerator = new NumberGenerator(1,11,2);
    private NumberGenerator evenNumberGenerator = new NumberGenerator(2,10,2);

    public void generateSeries(){
        oddNumberGenerator.generateNumbers();
        evenNumberGenerator.generateNumbers();
    }


    class NumberGenerator {
        private Thread thread;
        private int result;

        private NumberGenerator(final int initialValue, final int maxValue,
                                final int stepSize) {
            this.thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = initialValue; i <= maxValue; i = i + stepSize) {
                        try {
                            result = i;
                            cyclicBarrier.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (BrokenBarrierException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }

        public void generateNumbers() {
            thread.start();
        }
    }


    main(String[] args){
       new ThreadTest().generateSeries();
    }
}
2
Ronald Wildenberg On

You can have each thread generate numbers as follows:

Thread 1: 1, 3, 5, 7, 9, ...
Thread 2: 2, 4, 6, 8, 10, ...

add to a concurrent collection and sort afterwards.

3
kgautron On

Do they have to generate only one each time, or is it ok if thread1 generate 2 numbers, then thread 2 generates 1 number etc... ?

Use a static int field that will act as a counter, and access it in a synchronized way.

static int counter = 0;

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

Then the threads do :

while(...whatever..){
  System.out.print(getNextNumber());
}
1
Lakshmi Narayanan On
    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();
            }
        }


    }
0
Innocuous On

You can achieve using wait and notifyAll() . But it is always better to use standard java concurrent classes to achieve it

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

        final NumberValue number = new NumberValue();
        final Object lockObject = new Object();
        new Thread(){

            private NumberValue n  = number;
            @Override
            public void run() {
                synchronized (lockObject) {
                    while(n.getValue() < n.getEndPoint()){
                        while(n.isToggle()){
                            try{
                                lockObject.wait();
                            }catch(Exception e){
                                e.printStackTrace();
                            }
                        }

                        n.incrementValue();
                        System.out.println(getName() + " printing "+n.getValue());
                        n.setToggle(true);
                        lockObject.notifyAll();
                    }
                }
            }
        }.start();

        new Thread(){

            private NumberValue n  = number;
            @Override
            public void run() {
                synchronized (lockObject) {
                    while(n.getValue() < n.getEndPoint()){
                        while(!n.isToggle()){
                            try{
                                lockObject.wait();
                            }catch(Exception e){
                                e.printStackTrace();
                            }
                        }

                        n.incrementValue();
                        System.out.println(getName() + " printing "+n.getValue());
                        n.setToggle(false);
                        lockObject.notifyAll();
                    }
                }
            }
        }.start();
    }
}

class NumberValue {
    private int value;
    private boolean toggle = true;
    private int endPoint = 10;

    public int getEndPoint() {
        return endPoint;
    }

    public void setEndPoint(int endPoint) {
        this.endPoint = endPoint;
    }

    public boolean isToggle() {
        return toggle;
    }

    public void setToggle(boolean toggle) {
        this.toggle = toggle;
    }

    public  int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public synchronized void incrementValue(){
        this.value++; 
    }
}