【发布时间】: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