如何在Java中阻止函数?

问题描述 投票:0回答:1

我正在编写一个服务器-客户端程序,这是我的代码的简化图:

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
}

serverClass:

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阻塞,以便可以防止出现此问题?

java multithreading server blocking
1个回答
0
投票

问题是function1()似乎正在产生一个新线程来执行长时间运行的任务。但是它不等待它完成。因此,调用者(即您的main()方法)看不到getField1()的更改值。

您必须,

  1. 获得该长时间运行任务的Future或句柄,以便您可以选择阻止或等待它。
  2. 修改function1()以返回Future
  3. 等待未来
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());
}
© www.soinside.com 2019 - 2024. All rights reserved.