多线程中的多个扫描仪 [英] Multiple Scanners in Multiple Threads

查看:79
本文介绍了多线程中的多个扫描仪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚遇到有关Scanner(System.in)和Java中线程的问题.

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

假设您有两个线程.在这两种方法中,您都等待使用扫描仪的用户输入从System.in输入流中读取.问题在于,无法区分哪个字符串属于哪个线程(字符将在看似随机的两个字符串之间散布).我想这是因为两个线程共享相同的输入流.

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?

推荐答案

同步块将解决此扫描仪出现的问题.

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表示具有同步块的对象不允许两个线程同时访问该块内的代码.现在,我们在块中包含了关键代码,这意味着多个线程将无法同时访问 Scanner对象(输入).

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.

这篇关于多线程中的多个扫描仪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆