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();
}
}
>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)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.