javajava-threads

print number in order with thread


I want create two thread first one even and second one odd and I want have synchronized list to add this number and at last print number in order this is my codes

     @Override
    public void run() {
        synchronized (allNumber) {
            for (int i = 1; i <=number ; i+=2) {
                allNumber.add(i);
                try {
                    allNumber.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

        }
    }
     @Override
    public void run() {
        synchronized (allNumber){
        for (int i = 0; i <= number; i+=2) {
            allNumber.add(i);
            allNumber.notify();
        }
        }
    }
    public class Main {
    private static Scanner input = new Scanner(System.in);
    public static void main(String[] args) throws InterruptedException {

        System.out.print("Enter Your Number: ");
        int number = input.nextInt();

        List<Integer> sharedList = new ArrayList<>();

        Odd oddThread = new Odd(number, sharedList);
        Even evenThread = new Even(number, sharedList);

        Thread thread = new Thread(oddThread);

        Thread thread1 = new Thread(evenThread);

        thread.start();
        thread1.start();

        System.out.println("List: " + sharedList);

    }
}

my output is not in order and its not complete


Solution

  • I find one way this is my Even class code

    public class Even extends Thread {
        private final int input;
        private final List<Integer> allNumbers;
    
        private List<Integer> evenList = new ArrayList<>();
    
        public Even(int input, List<Integer> sharedList) {
            this.input = input;
            this.allNumbers = sharedList;
        }
    
        @Override
        public void run() {
            synchronized (allNumbers) {
                for (int i = 0; i <= input; i += 2) {
                    allNumbers.add(i);
                    evenList.add(i);
                    allNumbers.notify();
                    try {
                        if (i < input) {
                            allNumbers.wait();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            System.out.print("Even: " + evenList + " ");
            System.out.println();
        }
    }
    

    I do same for odd class then in main class create a list and pass it to Eeven and Odd class