(newbie) Thread problem

V

Vanessa Berni

Hi,
I'm trying to write a program that simulate traffic. I've got a class
"Scheduler" that simulate the movement of streets, cars ...
I've created an applet which calls a thread; in his method "run" I simply
call the method run of the Scheduler (which modifies cars position ...)
(action A) and then I repaint all the streets and cars (action B) then the
thread sleeps 30 millis (action C)

The thread start and so actions A,B,C, A,B,C, A,B,C, A,B,C ... are executed.
At a certain point while executing event B (repaint) the action A starts
again....
Why???

Can you please help me??

Thank you Vanessa

public class JSim extends JPanel implements Runnable{
public Thread runner = null;
public static Schedulatore scheduler = new Schedulatore();

public SimulatoreCanvas() {
super();
}

public void run() {
startTime = System.currentTimeMillis();
while (Thread.currentThread() == runner) {
try {
//action A
this.scheduler.run();

//action B
repaint();

//action C
Thread.sleep(30);

}
catch (InterruptedException e) { ;
}
}
}

public void start() {
if (runner == null) {
runner = new Thread(this);
runner.start();
}
}

public void paintComponent(Graphics g){
//... code that paints street objects
}
}
 
P

Paul Hamaker

repaint is only a request to have the component painted asap. This is
done in a separate thread, so the fact is, that repaint does not result
in paintComponent being executed immediately.
 
V

Vanessa Berni

Thank you
The problem is I CAN'T execute action A if action B is still running...

To try solving the problem I've added a boolean flag (canSim). If flag is
false action A won't be performed...

At the beginning of paintComponent I set it to false and at the end of the
method I set it to true. Is there another way??

Thanks Vanessa

boolean canSim=true;

public void run() {
startTime = System.currentTimeMillis();
while (Thread.currentThread() == runner) {
try {
//**********************
//**********************
if(canSim){

//action A
this.scheduler.run();

//action B
repaint();

//action C
Thread.sleep(30);
}

}
catch (InterruptedException e)
{
;
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top