我将从ServerData类发送数据到其他类时遇到问题。
问题是,在while循环中,数据被正确更新。如果我在while循环中执行System.out.println(inData);
或System.out.println(str);
以及System.out.println.(this.toString());
,则数据将如下所示:
ID=1144831794931864;X=218;Y=100;TYPE=3
ID=1144831794934430;X=268;Y=131;TYPE=3
ID=1144831794935712;X=107;Y=15;TYPE=2
ID=1144831794936140;X=27;Y=182;TYPE=3
不同的ID,坐标和类型。
但是,如果我尝试使用更新的字符串,如下所示:
while(true){
System.out.println(str); //shows same data/not updated.
}
或this.toString();
在另一个类中,显示相同的数据:
ID=1145076069027748;X=244;Y=73;TYPE=3
ID=1145076069027748;X=244;Y=73;TYPE=3
ID=1145076069027748;X=244;Y=73;TYPE=3
ID=1145076069027748;X=244;Y=73;TYPE=3
ID=1145076069027748;X=244;Y=73;TYPE=3
如您所见,所有信息都相同。 有谁知道我怎么能解决这个问题?
ServerData-class:
public class ServerData implements Runnable{
private long id;
private int xPos;
private int yPos;
private int type;
private String str;
private Thread thread;
private boolean running;
private Socket socket;
public ServerData(Socket socket){
this.socket = socket;
this.start();
while(true){
System.out.println(str); //shows same data/not updated.
}
}
public synchronized void start() {
running = true;
thread = new Thread(this, "Server");
thread.start();
}
public synchronized void stop() {
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run(){
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String inData = null;
try {
while((inData = in.readLine()) != null){
// System.out.println(inData);
str = inData;
this.setString(str);
String filteredData = inData.replaceAll("[^0-9;]", ""); //
String[] tmp = filteredData.split(";");
id = Long.parseLong(tmp[0]);
xPos = Integer.parseInt(tmp[1]);
yPos = Integer.parseInt(tmp[2]);
type = Integer.parseInt(tmp[3]);
// System.out.println(this.toString()); //shows correct data.
// System.out.println("ID: "+ id + " xPos: " + xPos + " yPos: " + yPos +" Type: " + type);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void setID(long id){
this.id = id;
}
public long getID(){
return id;
}
public int getXPos(){
return xPos;
}
public int getYPos(){
return yPos;
}
public int getType(){
return type;
}
public void setString(String str){
System.out.println(str); //shows correct data.
this.str = str;
}
public String toString(){
return str;
}
}