我希望有一个线程来更新其他类中的变量。
说,我有一个整数,一个有一个Socket获取值的线程类,我希望将该值设置为我的整数。
我的ENUM名为direction,其值为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;
}
}
我希望主类中的direction变量从线程类
更新答案 0 :(得分:1)
Socket socket = new Socket("myhost", myport);
DataInputStream dis = new DataInputStream(socket.getInputStream());
// read your value
int val = dis.readInt();
myClass.setValue(val);
在你的班级中,使用易变整数。
private volatile int value;
public void setValue(int val)
{
value = val;
}
确保线程有指向类实例的指针。例如,使用构造函数执行此操作。
答案 1 :(得分:1)
根据您发布的代码,您不需要做任何事情,只需读取变量(因为它在服务器中是易失性的):
Server server = new Server(...);
server.start();
//when you need it:
Direction dir = server.getDirection();
现在,如果您的问题是:我可以在获取服务器对象时获取dir
的各种值,您可以使用BlockingQueue
来处理通信。在Server类中,声明队列(并删除dir
成员):
private BlockingQueue<Direction> queue = new LinkedBlockingQueue<Direction> ();
然后在你的run方法中:
Direction dir = Direction.fromInt(recieved);
queue.put(dir);
您的getDirection
方法可以重命名为getNextDirection
:
public Direction getNextDirection() throws InterruptedException {
queue.take();
}
你的主人可能看起来像这样:
while (true) {
Direction nextDirection = server.getNextDirection()
//do something with the new direction
}
注意:我已重命名您的枚举Direction
而不是direction
以尊重Java命名约定。