1

So I am a beginner in java.

Yesterday while writing a code for thread synchronization I came across an error java.util.NoSuchElementException. Code and the error are specified below. Here the shared variable among threads is a. From what I can guess from the error the variable b is having problems in taking the second value.


        class Sum
        {
            synchronized void addition(int a)
            {
                Scanner sc = new Scanner(System.in);
                System.out.println("enter vale of b: ");
                int b = sc.nextInt();
                sc.close();
                int c = a + b;
                System.out.println(c);
            }
        }
        class ThreadP1 extends Thread
        {
            Sum s1;
            ThreadP1(Sum s1)
            {
                this.s1 = s1;
            }
            public void run()
            {
                Scanner sc1 = new Scanner(System.in);
                System.out.println("enter element a: ");
                s1.addition(sc1.nextInt());
                sc1.close();
            }
        }
        class ThreadP2 extends Thread
        {
            Sum s1;
            ThreadP2(Sum s1)
            {
                this.s1 = s1;
            }
            public void run()
            {
                Scanner sc2 = new Scanner(System.in);
                System.out.println("enter element a: ");
                s1.addition(sc2.nextInt());
                sc2.close();
            }
        }
    
    
    
        public class Synchronisation1 
        {
            public static void main(String args[])
            {
                Sum obj3 = new Sum();
                ThreadP1 t12 = new ThreadP1(obj3);
                t12.start();
                ThreadP2 t13 = new ThreadP2(obj3);
                t13.start();
            }
        }

Error

>Thread-1 java.util.NoSuchElementException  
        >>at java.base/java.util.Scanner.throwFor(Scanner.java:937)
        >>at java.base/java.util.Scanner.next(Scanner.java:1594)   
        >>at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
        >>at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
        >>at Sum.addition(Synchronisation1.java:8)
        >>at ThreadP2.run(Synchronisation1.java:40)
Most Noble Rabbit
  • 2,728
  • 2
  • 6
  • 12
  • 2
    You have closed a Scanner built on System.in. Closing the scanner closes System.in, and it cannot be reopened. Solution, do not close the scanner until the program ends. – NomadMaker May 08 '21 at 05:02

1 Answers1

0

As commented, by closing the Scanner, you close the System.in. The latter scanner will get an exception when it realizes System.in is closed.

One way to fix it will be not to close the scanner.

By the way, ThreadP1, ThreadP2 seem to do the same thing. Consider creating 2 instances of the same class instead.

Most Noble Rabbit
  • 2,728
  • 2
  • 6
  • 12