Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I just encountered a problem concerning the Scanner(System.in) and threads in Java.

Suppose you have two threads. In both you wait for an user input using the Scanner to read from the System.in input stream. The Problem is that it is not possible to differentiate which string belongs to which thread (the chars will be spread between both strings seemingly random). I suppose this is because the two threads share the same input stream.

Is there a way to work around this issue?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
287 views
Welcome To Ask or Share your Answers For Others

1 Answer

Synchronized block will solve this scanner concerning problem.

public class Threader implements Runnable {

    private String name;
    private Scanner input;

    public Threader(String name,Scanner input) {
        this.name = name;
        this.input = input;
    }

    @Override
    public void run() {
        synchronized (input) {
            System.out.print(name + " : " + input.nextLine());
        }
    }

}

Pass the scanner object in every new thread.

Synchronized means an object having synchronized block does not let two threads to access the code inside the block at the same time. Now we have the critical code inside the block, which means multiple threads won't be able to access the Scanner object (input) at the same time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...