且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

多线程中的多个扫描仪

更新时间:2023-01-11 21:05:52

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

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.