我想要一个线程来更新其他类中的变量。
假设,我有一个整数和一个线程类,其中有一个可以获取值的 Socket,并且我希望将该值设置为我的整数。
我有一个名为 Direction 的 ENUM,其值为 UP、DOWN 我有一个主类,它有一个方向变量 在那个主类中,我正在启动一个线程,其中有一个套接字 该线程看起来像:
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server extends Thread {
private ServerSocket serverSocket;
DataInputStream in;
volatile direction dir;
public Server(int port,direction d) throws IOException {
serverSocket = new ServerSocket(port);
Socket server = serverSocket.accept();
in = new DataInputStream(server.getInputStream());
dir=d;
}
public void run() {
int recieved;
while (true) {
try {
recieved = in.readInt();
while (recieved != -1) {
dir = direction.fromInt(recieved);
recieved = in.readInt();
System.out.println(dir);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public direction getDirection() {
return dir;
}
}
我希望主类中的方向变量从线程类更新
最佳答案
Socket socket = new Socket("myhost", myport);
DataInputStream dis = new DataInputStream(socket.getInputStream());
// read your value
int val = dis.readInt();
myClass.setValue(val);
在你的类中,使用 volatile 整数。
private volatile int value;
public void setValue(int val)
{
value = val;
}
确保线程有一个指向您的类实例的指针。例如,使用构造函数来执行此操作。
关于Java让线程更新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13862256/