我正在编写一个服务器客户端程序,这是我的代码的简化版:
public static void main (String[] args){
function1();
System.out.println(object1.getField1());
}
客户类别:
class client {
public function1(){
//connecting to server and writing the field value to dataOutoutStream
}
服务器类:
class Server{
//accepting client and reading the value from dataInputStream
new Thread(new Runnable() {
public void run() {
object1.setField1(//something);
}
}
}).start();
}
在 function1 的某个位置,我连接服务器,它运行一个线程来更改 object1 的 field1。
但问题是,在字段实际更改之前,它会打印以前的值。 如何使 function1 阻塞以防止此问题?
最佳答案
问题是 function1()
似乎正在生成一个新线程来执行长时间运行的任务。但它不会等待它完成。因此,调用者(即 main()
方法)看不到 getField1()
的更改值。
你必须,
- 获取
Future
或长时间运行任务的句柄,以便您可以选择阻止或等待它。 - 修改 function1() 以返回 Future
- 等待 future
private static final ExecutorService executorService = Executors.newSingleThreadExecutor();
private Future<?> function1() {
return executorService.submit(() -> {
// your long running task which updates **field1**
});
}
public static void main (String[] args){
Future<?> resultFuture = function1();
// wait on this future , i.e. block
resultFuture.get();
System.out.println(object1.getField1());
}
关于java - 如何在java中使函数阻塞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62435877/