views:

297

answers:

2

I'm kinda new to Java, so haven't yet fully grasped the concept of multithreading.I would like to create a PIDController class that allows me to do this:

ControllerMethods methods = new ControllerMethods()
                            {
                                public long getError(long setpoint)
                                {
                                 //get an input
                                }
                                public void setOutput(long value)
                                {
                                 //do something
                                }
                                public void isComplete(long setpoint)
                                {
                                 return getError() == 0;
                                }
                            };

PIDController motorPID = new PIDController(setpoint, kp, ki, kd, methods);

motorPID.run();
//runs the PID controller to completion (methods.isComplete() == true)

motorPID.run(false);
//starts the PID controller in a separate thread, allowing
//continual monitoring in the current thread

while(motorPID.isRunning())
{
    //do something else
    if(condition1)
     motorPID.pause();
     //pause the PID controller, preventing the integral from increasing
    else if(condition2)
     motorPID.stop();
}

I've worked out how to calculate the standard PID argorithms, but I can't work out how to provide the asynchronous functionality.

Can anybody tell me how I can achieve a similar API?

A: 

you can try standard Java classes such as ProcessBuilder and Process

dfa
He is asking for advice on Java Threads (like tangens' reply) not asking how to spawn processes.
rsp
my answer is about studying that classes, not using them directly
dfa
+1  A: 

You already implemented a run() method for PIDController so you should also implement the Runnable interface:

class PIDController implements Runnable {
    ....
}

Now you can start your PIDController asynchonous, by calling:

pidControllerThread = new Thread( pidController );
pidControllerThread.start();

For synchronization (if needed) you should have a look at the sun concurrency guide.

tangens
If you want better control, then let an Executor (many in the ExecutorService) manage it instead of having a loose Thread running around. http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html
Thorbjørn Ravn Andersen
At present, my `PIDController` class has an instance of an inner class derived from `Thread`. I can't really decide whether the controller shoud be a `Thread` or contain a `Thread`
Eric
I'd recommend moving the multithreading code out of your PIDController class, and into a PIDManager or something, which is in charge of setting up PIDControllers in separate threads.
Sam Barnum