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)