问题
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?
回答1:
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.
回答2:
My run() method its a switch which calls another method of its own class.Im using BufferedReader with Sockets.Im trying to synchronize everything but i cant!!There is other way?I let u here a part of my code:
NOTE:YOU CAN FORGET EVERYTHING BUT "DIS,DOS,BF" I THINK THERES THE PROBLEM!
Im trying to Synchronize the BufferedReader and the DataOutputStream here
private void escribir(Socket clientsocket,BufferedReader br) {
try {
dos = new DataOutputStream(clientsocket.getOutputStream());
dos.writeUTF(String.valueOf(identificador));
}catch(Exception e) {
e.printStackTrace();
System.out.println("Error creando as canles");
}
synchronized(br) {
synchronized(dos) {
try {
while(clientsocket.isConnected()) {
String datosenviar=br.readLine();
dos.writeUTF(datosenviar);
}
}catch(Exception e) {
System.out.println("Bot desconected");
}
}}
}
I ´ve thought the problem may be the client input so i did the same:
private void leer(Socket clientsocket){
try {
dis = new DataInputStream(clientsocket.getInputStream());
}catch(Exception e) {
e.printStackTrace();
System.out.println("Chanel not created");
}
synchronized(dis) {
try {
while (clientsocket.isConnected()) {
String datosentrada = dis.readUTF();
if(datosentrada.contains("1234Broadcast:"))System.out.println("Bot Master says:"+datosentrada.substring(14));
else if(datosentrada.contains("1234Bot"+identificador+":"))System.out.println("Bot Master says:"+datosentrada.substring(8+identificador.length()));
}
}catch(Exception e) {
e.printStackTrace();
System.out.println("Something Wrong happens here");
}
}}
Anyways, when i have 2 clients i need to write the same thing 2 times... I hope you can help me and im sorry for the great doubt
来源:https://stackoverflow.com/questions/43460771/multiple-scanners-in-multiple-threads