【问题标题】:Program1.run(Program2); HowTo: Program2.finish()?Program1.continue():Program1.wait();Program1.run(程序 2);如何:程序 2.finish()?Program1.continue():Program1.wait();
【发布时间】:2014-07-12 00:04:55
【问题描述】:

我有两个 Java 程序。 “第一个”/“主要”实现搜索算法,“其他”/“第二个”使用 Repast 模拟框架来运行多智能体模拟。在“第一个”Java 程序中,我有以下代码块:

Class Individual{

public int getvalue()
{

While (Condition is true)
{
  Start_MAS();   //start the simulation by calling the "second" Repast simulation program  
                 //which will write some values to a text file at the end of the simulation

  //read text file and do some work with the values
}
}}

MA 模拟/“秒”程序将运行模拟,直到满足特定条件或经过 900 个时间步长,一旦满足停止条件,程序会将一些输出写入文本文件,即由“第一个”程序读取。 现在我的问题是,当我运行“第一个”程序(在某些时候调用/运行第二个程序/模拟)时,它不会等待模拟/“第二个”程序完成,但会发生什么之后运行模拟/“第二个”程序时,“第一个”程序将继续运行它自己的代码,该代码正在读取输出文本文件,所以我收到文本文件为空的错误。

我的问题是如何强制“第一个”程序等待或停止运行其代码,直到“第二个”/模拟程序完成(满足停止条件并将输出写入文本文件)?我想在“第一个”程序中使用等待并在“第二个”程序中通知如下:

在“第一个”程序中:

Class Individual{

public int getvalue()
{

While (Condition is true)
{
  Start_MAS();     //start the simulation by calling the "second" program which will write some 
                   //values to a text file at the end of the simulation


  synchronized(this) 
     {
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    //read text file and do some work with the values
 }
}

在“第二”程序中:

public void step(){         //a function called in each time step in the simulation
  If (Stop condition is met)
     MyPackage.Individual.notify();
                 }

但是如果我这样做,它将在从“第二个”程序返回后执行等待,并且如果我将它放在调用之前,它将等待然后开始模拟。是否使用等待并通知正确的方法来执行此操作?有关如何完成此操作的任何建议或提示?

非常感谢!

【问题讨论】:

  • 不显示实际细节,没有人可以帮助你。
  • 您对“项目”一词的使用含糊不清。您是指程序还是应用程序?我们也不知道“Repast”是什么意思。您的要求太模糊和令人困惑。您可以发布一些可运行的示例代码吗?您可能想研究“Java 并发”。 How to create a Minimal, Complete, Valid Example.
  • 我假设 repast 是搜索中出现的模拟框架。无论如何,我不得不同意我们可能需要更多细节。您最好使用 Callable/Future 来简化代码,这样您就不必等待/通知。
  • 你可以让它们都打开同一个套接字——等待的程序在第一个程序释放它之前不能打开它。
  • 项目不运行。程序运行。请澄清您的问题。

标签: java wait notify project-reference


【解决方案1】:

我怀疑你的 Repast 模拟真的提前终止了,因为从你的第一个应用程序以编程方式运行它和你单独测试第二个程序(Repast 模拟)之间的条件有所不同。

因此 - 我建议您在停止条件块中放置一些调试语句,以在返回之前检查模拟是否真正停止。如果是这样,您有一个不同的问题要询问模拟停止的原因,而不是关于进程/线程的问题。例如

...
If (Stop condition is met)
{
    System.out.println("Stop condition has been met at tick " + 
      RepastEssentials.getTickCount());
}
...

我还建议您加入就餐兴趣列表以获得这些问题的答案(我不是 Repast 项目的成员,但请经常使用它)。这类问题经常被问及并得到解决,列表处于活跃状态。

注意关于这个确切问题的最新帖子已解决 here(发布以供参考 - 尽管查看了其中的数字,也许这个问题来自您?)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-11
    • 2012-04-05
    • 2016-09-30
    • 2019-03-16
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 2019-09-17
    相关资源
    最近更新 更多