Program1.run(Program2); HowTo: Program2.finish()?Program1.continue():Program1.wait(); - java

I have two Java programs. The "first"/"Main" one implements a search algorithm and the "other"/"second" one uses Repast simulation framework for running a Multi-agent simulation. In the "first" Java program I have the following code block:
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
}
}}
the MA simulation/"second" program will run the simulation until a specific condition is met or 900 time-steps has elapsed, and once the stop condition is met, the program will write some output to a text file, which is read by the "first" program.
Now my problem is that when I run the "first" program (which at some point calls/runs the second program/simulation), it does not wait for the simulation/"second" program to finish, but what happens is that after sometime of running the simulation/"second" program, the "first" program will continue running its own code which is reading the output text file so I get error that the text file is empty.
My question is how do I force the "first" program to wait or stop running its code until the "second"/ simulation program is finished (the stop condition has been met and output has been written to the text file)? I thought of using wait in the "first" program and notify in the "second" program as follows:
In the "first" program:
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
}
}
In the "second" program:
public void step(){ //a function called in each time step in the simulation
If (Stop condition is met)
MyPackage.Individual.notify();
}
but if I do this, it will execute wait after returning from the "second" program, and also if I place it before the calling it will wait then start the simulation. Is using wait and notify the correct way to do this? Any suggestions or tips on how to accomplish this?
Thank you so much!

I suspect your Repast simulation is genuinely terminating early due to some difference in conditions between running it programatically from your first app and when you have tested the second program (Repast simulation) stand alone.
Therefore - I recommend that you put some debug statements in your stop condition block to check whether the simulation is genuinely stopping before returning. If so, you have a different question to ask about why the simulation is stopping, rather than one on processes/threads. e.g.
...
If (Stop condition is met)
{
System.out.println("Stop condition has been met at tick " +
RepastEssentials.getTickCount());
}
...
I also suggest you join the repast-interest list to get answers to these questions (I am not a member of the Repast project, but do use it regularly). These kinds of questions are often asked and resolved, the list is active.
N.B. most recent thread on this exact issue was resolved here (posted for reference - although looking at the numbers in there, maybe that question is from you?).

Related

program flow in recursive method in java

class Test {
int i=0;
void method2() {
if(i==6) return;
System.out.print("before");
i++;
method2();
System.out.println("after"):
}
}
If I call method2() from another class then I want to know how the program will flow here or why the output that's executed.
In depth knowledge of recursion can be found here
https://en.m.wikipedia.org/wiki/Recursion_(computer_science)
As far as your program is concerned it will stop when i=6
Otherwise it will keep on printing before.
This is because in programming the flow of control is never skipped it follows the flow of control but it is not that it leaves the rest statement so whenever a new call to a function is generated the previous status of the functioning is being pushed in stack one by one and so the stack is kept on increasing and when finally the end condition is reached it pops all function calls one by one from the activation record and does the required processing is done and thus recursion works.
It takes help of a stack for doing operations.
The program flow always follows it's order wheather you call it from anywhere.
So the program flow remains same.
You will easily understand the working if you run it and add some more print statement with also the values of i.

Prevent Thread Subclass from waiting

I'm making a coding game for the Java class I TA. The game is to manage a fleet of trucks (Truck extends Thread) on an undirected graph to deliver parcels to their various destinations using as little time/fuel as possible. The student extends an abstract manager class that fills in the gaps in the Truck's behavior (what to do upon reaching a destination, etc). The truck class's run method is a event loop that waits for user instruction and then follows it when it receives travel destinations. Here's the event loop:
#Override
/** The Truck's main running routine. While the travel directions are empty,
* Waits for more instructions in WAIT_TIME intervals. While the travel directions
* are not empty, pops off the next travel direction
*/
public void run(){
while(game.isRunning()){
setGoingTo(null);
while(travel.isEmpty() && game.isRunning()){
try{
Thread.sleep(WAIT_TIME);
}
catch (InterruptedException e){
e.printStackTrace();
}
setStatus(Status.WAITING);
game.getScore().changeScore(Score.WAIT_COST);
}
while(!travel.isEmpty() && game.isRunning()){
Edge r = getTravel();
try {
travel(r);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
The first inner while loop loops while there are no travel instructions to follow. As you can see, every WAIT_TIME milliseconds (a frame), the score is decreased by the wait cost - the cost of the truck idling.
I realized, however, that a way for a potential solution to get around this cost is to tell the truck (thread) to wait while it doesn't have instructions, then notify it once the user has computed instructions for it. I'd like to prevent this programmatically, rather than just put in the instructions not to do it.
Is this even possible? Perhaps a method in the thread class to override? Can a class that extends Thread be prevented from waiting (on anything?) I'd settle for any kind of exception being thrown if a truck thread tries to execute .wait().
Thanks for reading and for any suggestions for how to tackle this gap in the rules! The game will be up on a public repo soon if you want to try your hand at it.
I don't have a solution for the exact question you asked (how to prevent wait), but a suggestion that is kind of too long for a comment:
How about measuring the time between the start of the first while loop and the end.
long starttime = System.currentTimeMillis();
setStatus(Status.WAITING);
while(travel.isEmpty() && game.isRunning()){
try{
Thread.sleep(WAIT_TIME);
}
catch (InterruptedException e){
e.printStackTrace();
}
}
long endtime = System.currentTimeMillis();
long waittime = endtime - starttime;
game.getScore().changeScore(Score.WAIT_COST * (1 + waittime / WAIT_TIME));
Even if the thread is sent to sleep, the score will change according to the ellapsed time. You will just not have a live game score update.
I'm pretty sure you can't prevent .sleep() or .wait() because you can't override or tamper with them. So the only way is monitoring for them.
I don't know of a method inside the thread but from outside the thread (for example from a monitoring thread) you can get the thread staus with
Thread.getState()
if someone called sleep on the thread or the thread is waiting becuase of a wait call the result should be Thread.State.TIMED_WAITING. Then all you have to ensure is that the monitoriong thread knows it were the students that called sleep and not you (a private flag for example).
The monitoring thread can then of course take any counter measures you want like throwing an Exception or simply silently decucting points.
Relevant docs :
http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.State.html#TIMED_WAITING
http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#getState()
I wonder whether having a Thread per Truck is the right approach. Are you trying to teach them about threads? or are you trying to teach them about graph algorithms and heuristics? (If the Single Responsibility Principle applies to homework assignments, then the answer should be one or the other, but not both.)
If the emphasis was on algorithms and heuristics, then I would write a single-threaded program where the main loop executes a series of "moves". In each move, it would ask each of the truck objects what the truck wants to do next, and then it would either move the truck accordingly, or it would flag the assignment as invalid if the truck asked to do something that did not make sense.
In my version, the "time" in the simulation would be completely decoupled from real-time, so if some student put a Thread.sleep() in her/his strategy routine, it would not have any effect on the outcome of the program; it only would make the program take that much longer to run. (Of course, I would run them all under control of a batch script that would abort any assignment that took longer than... say, three minutes.)

Handling Python IO from Within Java

I am currently working on a Java project that will allow me to text edit, save, and then execute Python code. I have hit a snag with the execution of this code however.
For executing the code, I have been doing the following:
Process p = Runtime.getRuntime().exec("python someFileName.py",null,new File("someFilePath");
From here, I have a class that takes this process, and tries to take the input and output streams from the process. I have a Timer set with an action listener that will refresh every .01 second.
That is not the problem however. I can receive input just fine if my program consists solely of print statements in python.
If my program contains anything that requires it to block, either raw_input or time.sleep, nothing is displayed.
My actionPerformed method is as follows:
public void actionPerformed(ActionEvent e)
{
try
{
while(inStream.available() > 0)
{
System.out.print((char)inStream.read());
}
while(errStream.available() > 0)
{
System.out.print((char)errStream.read());
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
To handle output, I have a KeyListener on a JTextArea that will send the contents of that area to the output stream.
Whenever I have anything in my Python program that requires blocking, no matter what location in the program, the entire thing locks up.
For instance, I have this python program:
import time
print "Welcome to my Program!"
print "Performing calculations"
time.sleep(5)
num = 5
print "Adding 5 to your number"
for x in range(5):
num+=1
print num
print "Finished!"
Nothing will display for the time that it sleeps. I would assume that the things I receive in the Java program would be:
Welcome to my Program!
Performing calculations
...then nothing for five seconds...then
Adding 5 to your number
6
7
8
9
10
Finished!
But nothing is displayed at all until after 5 seconds has elapsed. So I can execute the program, wait 5 seconds, then a flood of text appears.
Or for using raw_input, the same thing happens. So in other words I cannot use this to prompt users for input.
I was hoping I could get some help with this blocking issue so that my text displays gradually as opposed to having to wait for everything to get out of the way with timers or input.
Any help or resources are appreciated. My current OS is a Mac, but I want any solution to be workable on Windows as well (if at all possible).
By default, python scripts run with buffered output. That means you may not see any stdout until the script exits and flushes. All you have to do is launch python with -u to request unbuffered output. Then you will see what you were expecting.
python -u someFileName.py

long running application (tail like)

I want to write an tail like app. Now this app, scans a file for changes in the background and fires events in case something changed.
I want to run my application until the user requests to exit it by pressing ctrl + c (working by default). I do not want to create a lot of CPU load just by doing an endless while(true) loop like I'm doing ATM:
try {
// thread doing the monitoring
thread.start();
// forcing the programm not to exit
while (System.in.available() == 0) {
Thread.sleep(5000);
}
} catch (final IOException e) {
e.printStackTrace();
}
Does anyone know a more elegant/the right approach for this?
I'm not sure why you are using a thread in the first place, the 'tail' unix script is simply a while(true) loop with no exit condition. It watches the file and prints changes if any is detected. I think by default it pauses 1 second, so basically:
while(true) {
// Code goes here. Watch file, System.out.print if it changes
Thread.sleep(1000);
}
No need for a thread. But to answer the question about the best way to keep your app alive: Simply don't return from the thread's run() method. You don't have to join the thread, the application will stay in the foreground as long as it has one non-daemon running thread.
If you want to read the System.in without busy-waiting, that's very easy to achieve. InputStream has blocking semantics so all you need to to is call one of the read methods and it will block until there is input available. If you are scanning text input, I'd advise BufferedReader.readLine. Also, do that on the main thread, no point in starting another one.

UI updates as expected in debug mode, but does nothing when run normally

I'm creating a simple game turn based game in NetBeans. After the initialization of the GUI it calls the function herosTurn() to which waits for the users choice and and creates the outcome of that choice from a separate class Hero. When I step through the code in Debug mode, I get correct outcomes, but if I just run the code nothing is ever appended to the Text Area unless I have the wait function constantly appending text while it waits for input. I've seen other questions similar to this but they all involved multi-threading, and I don't believe that is what I am doing. Any help would be greatly appreciated.
This is the main class:
package Flow;
import Forms.Battleinterface;
/**
*
* #author Steemo
*/
public class battle {
public static int hAct;
public static int gLife = 200;
public static void herosTurn() {
hAct = 0;
Forms.Battleinterface.biText.append("What will you do?");
while (hAct == 0){
// adding the line below makes code work but is ugly.
//Forms.Battleinterface.biText.append(".");
continue;
}
if (hAct == 1){
Entities.Hero.attack();
}
}
public static void main(String args[]) {
Battleinterface battleinterface = new Forms.Battleinterface();
Battleinterface.Start();
while (gLife > 0) {
herosTurn();
}
}
}
And this is the Hero() class that is in a separate package:
package Entities;
import java.util.Random;
/**
*
* #author Steemo
*/
public class Hero {
static Random hGen = new Random(54154454);
public static void attack() {
int hAtt = 0;
hAtt = hGen.nextInt(6) + 15;
Forms.Battleinterface.biText.append("\nYou swing your axe and do " + hAtt
+ " Damage!!!");
}
}
I am not attaching the class I use to generate the GUI (Battleinterface) because the GUI generates fine and the only other thing happening there is the passing of the input hAct.
If it is needed I can attach it.
Replace this code...
while (hAct == 0){
continue;
}
...with this instead:
while (hAct == 0){
try {
Thread.yield();
} catch (InterruptedException interruptedEx) {
// Log the interruption somewhere.
}
}
Assuming you're using AWT/Swing on some level? This is an infinite loop, preventing other threads from ever running. By doing this you never let the UI thread actually do any updating, which means it appears to hang. You may not be doing any threading on your own, but AWT/Swing comes with Threads built in to do various functions, and they need to periodically get CPU time to do their work.
The reason this works in debugging is because the debugger is pausing the herosTurn method as you're stepping through it, allowing the UI thread to do its updates (including getting input from the user), but when simply running your game, the herosTurn method never pauses, and that method is occupying 100% of the available CPU time for your app.
Finally, as Mike Clark mentions, you typically shouldn't write UI with infinite loops. Instead you define components, which trigger events. Your code is notified of those events and reacts appropriately. This is what is known as the UI's event model. If you're using Swing, the introductory info on working within the event model is covered here.
I also wouldn't typically use AWT/Swing for games, because of the complications of UI coding, rendering performance, and several other reasons relating to the reality that AWT/Swing were not built to be good tools for games. That being said, a turn-based game can work fine this way (because the rendering performance requirements are often much lower) if you're willing to delve into the UI code to get it done, in addition to a few other reasons which I've outlined in a previous answer.
Hmm, there might be an issue with flushing your text buffer to the text area. Try explicitly flushing your text buffer after every print to see if that makes a difference.
It seems to me that your program is stuck in a while loop in the method herosTurn() As long as that function has not returned, nothing is going to update if you program this game as a single thread application.
It works when you uncomment the Forms.Battleinterface.biText.append("."); line cos then you send a signal to the GUI every iteration which causes it to update.
Games usually have a main game loop from which all elements of the program are controlled. Maybe a change of your implementation strategy will help?
I'm not a games programmer, so this might not be the best approach, but why don't you try setting up a javax.swing.Timer that runs every, say, 100 milliseconds. In inside the timer action, you can write all the code which checks and advances the game state and generates output to the user.
I'd suggest collecting the user's input in a JTextField that is separate from the place where the game output is printed. If you want to know when the user presses enter to send what they've typed, you can register an ActionListener on the JTextField.
textField.addActionListener(yourListener);

Categories

Resources