multiple threads

hi,

i've got a problem with multiple threads.

i have written a small "traffic simulation" with the following code:

publicvoid start()

{

animator =new Thread(this);// create new thread

light =new Thread("light");

animator.start();// start thread

light.start();

}

/**

* This method is called by the thread that was created in

* the start method. It does the main animation.

*/

publicvoid run()

{

// Remember the starting time

long tm = System.currentTimeMillis();// get time (ms) and store it in tm

while (Thread.currentThread() == animator)

{

// Display the next frame of animation.

if (frame==(200*roadArrangement.size()+50))// if object reaches "end" reset

{

frame =-50;// "reset" frame

}

repaint();// repaint object

//validate();

// Delay depending on how far we are behind.

try

{

tm += delay;// delay

Thread.sleep(Math.max(0, tm - System.currentTimeMillis()));

}

catch (InterruptedException e)// catch exception for thread

{

System.out.println("error in thread interrupt!");

break;

}

frame++;// Advance the frame

setPos();

}

publicvoid paint(Graphics g)

{

Image jct_img = java.awt.Toolkit.getDefaultToolkit().getImage("junction.jpg");

Image rd_img = java.awt.Toolkit.getDefaultToolkit().getImage("street.jpg");

for(int i = 0; i < roadArrangement.size(); i++)

{

int red = 0;

String tempType = roadArrangement.elementAt(i).toString();

char roadType = tempType.charAt(0);

g.setColor(Color.darkGray);

if(roadType =='r')

{

//g.drawImage(rd_img,10+(i*200),100,null);

g.setColor(Color.darkGray);

g.fill3DRect(10+(i*210),100,210,60,true);

}

elseif(roadType =='j')

{

//g.drawImage(jct_img,10+(i*200),30,null);

g.setColor(Color.darkGray);

g.fill3DRect(10+(i*210),100,210,60,true);

g.fill3DRect(85+(i*210),160,60,70,true);

g.fill3DRect(85+(i*210),30,60,70,true);

[b]g.setColor(Color.red);// colour of traffic light[/b]

[b] g.fillOval(10+(i*210)+50,30+100,10,10);// traffic light[/b]

Color clr = g.getColor();

red = clr.getRed();

}

if((frame == (10+(i*210)+50))&&(red==255))

{

System.out.println("STOP");

}

}

}// end of paint instance method

What I would like to do is, that my traffic lights change their colours randomly to red and then after a few second (e.g. 2sec) back to green.

How can I program that, shall I use a second thread?

Thanks in advance.

[4956 byte] By [sanva] at [2007-11-26 20:47:10]
# 1

If the time interval is constant then you could use a Timer/TimerTask to fire an event to do the change. Otherwise you'll need a thread to fire the event when needed.

GUI programming technique questions are often better asked in a GUI forum, eg Swing forum. Those guys deal with this sort of thing all the time.

davidholmesa at 2007-7-10 2:09:48 > top of Java-index,Core,Core APIs...