Click to See Complete Forum and Search --> : Threaded Java Help


dougal85
03-29-2007, 07:56 AM
OK, Since there is usually at least somebody on here at knows everything. Here comes a fun Java Question.

I have never done programming with multiple threads before. I have only used one thread to create a delayed loop. Using sleep.

What confuses me, is i want to have a main program that runs... then there are two threads one running every 100 ms and one running every 400 ms.

OK so far.

However, they also share resources. By that I mean, depending on the result of there execution on each thread it effects the program. I just don't know how to pass the variables around.

So for example.

there is a motor class
every 100 ms the motor heat sensor is checked. if its too high it stops the motor
then every 200ms the moisture sensor is checked. if its too high the motor stops.

(if the motor is not running and the sensors are not too high they start the motor)

Can anybody give me a rough pointer as to where to start with this. As i see it so far,

Main Class (initializes, starts threads)
heat sensor class (polls heat)
moisture sensor class (polls moisture)
motor class (manages motor on/off etc.)

I just don't know how to get the information from the threads to the motor class.

Thanks again, hope this makes sense :-/

bubblenut
03-29-2007, 08:26 AM
Remember you're working in an OO environment, so just pass around an object. The obvious one here would be Motor, then have each of the Sensors call Motor's stop method if their switch it tripped. You will have to synchronize Motor's stop method to avoid both Sensors accessing it at the same time as that could cause strange things to happen.

That's be basic idea, now for a little detail. Your Sensors either implement Runnable or extend Thread, it doesn't really matter which so I'll go with implementing Runnable. You could make an instance of Motor a requirement on the constructor or have it set via a setter, as the Sensors don't mean much without a Motor I would make it a dependency.


public class HeatSensor implements Runnable {
private Motor motor;
public HeatSensor( Motor motor ) {
this.motor = motor;
}
public void run() {
while( true ) {
Thread.sleep( 10 /* or whatever */ );
if( /* temperature too hot */ ) {
motor.stop();
}
}
}
}


Then in your entry point

public class EntryPoint {
public static void main( String args[] ) {
Motor motor = new Motor();
HeatSensor heat_sensor = new HeatSensor( motor );
Thread heat_sensor_thread = new Thread( heat_sensor );
heat_sensor_thread.start();
motor.start();
}
}

dougal85
03-29-2007, 05:00 PM
I think your right, I am looking at it as if it was more complicated than it is.

I think threads are just one of those things that scare me :rolleyes:

I guess also, things start to get messy when you are passing around lots of objects