I am currently working on a project in JAVA where I have to make an agent to interact with a server.

Each 50ms, the server will receive the last thing I outputted to System.out and send me a new set of lines as a 'state' through the System.in printstream to analyze and send my next message to System.out.

Also, if the server receives multiple outputs from me, it only regards the most recent one.

..

As for my question:

My program originally constructed a tree and then analyzed each leaf node to see which would be optimal, and then waited around for the next input, but I can recursively do a deeper tree search that would make my output 'better' (and again and again to keep returning a better result).

Using this and the fact that if the server receives multiple outputs, it only takes the most recent one, I could do each level, print my result and start the next level. But here comes my problem...

I can't be stuck in some complex algorithm while I am supposed to receiving the next input as I will then miss it. So I was wondering if there is a way to cancel anything else I am doing when I receive something via System.in and then go back to the beginning of the function and start the search again with the new set of input (and rinse and repeat..)

1 Answer
1

I assume that you've solved the problem of receiving input into System.in, as well as the problem of your algorithm. The next step is to package each in a Runnable interface, and hand each a reference to a queuing object. This will scaffold a Producer-Consumer relationship.

Whenever your listening Runnable (the Producer) gets a message, it needs to put it on your queue. After every unit of work, your algorithm (the Consumer) should look into the queue for items that are there. If it finds something, it should integrate it as normal. If not, it continues on with it's work.

Both the Producer and the Consumer need to be started in their own threads and allowed to run concurrently.

Hey thanks, still learning the ropes with programming and somehow I've never properly dealt with threads... but have done some reading and this looks perfect..
–
RonaldSep 26 '12 at 16:38

No problem! Once you have a handle on this, look up the 'Dining Philosophers' problem.
–
Nathaniel FordSep 26 '12 at 18:24

I've actually come across the Dining Philosophers before but I never did anything past the theory.. Concurrency and Synchronization look like a tricky business if approached in the wrong manner... Anyway, I've already Implemented the idea you recommended and it's working like a charm .. Can't thank you enough
–
RonaldSep 26 '12 at 23:52