【问题标题】:how to make a function blocking in java?如何在java中使函数阻塞?
【发布时间】:2020-10-07 16:16:21
【问题描述】:

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

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阻塞,这样我就可以防止这个问题?

【问题讨论】:

  • 您需要与该线程进行某种协调。如果不了解它的作用/方式,我们将无法为您提供任何进一步的帮助。
  • 如果可能的话,我建议通读所有docs.oracle.com/javase/tutorial/essential/concurrency。它有非常好的建议。
  • 你可以在这里尝试使用观察者模式journaldev.com/1739/observer-design-pattern-in-java
  • @SotiriosDelimanolis 我试图带来我的代码的简化视图
  • 您可以在服务器中集成某种CountDownLatchCompletableFuture,并将其作为function1 的返回值公开。

标签: java multithreading server blocking


【解决方案1】:

问题在于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());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-08
    • 2020-03-29
    • 2015-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多