先给currentRunning一个初值,如
public void start()
{
currentRunning="blue";
t1=new Thread(this,"blue");
t2=new Thread(this,"red");
t1.start();
t2.start();
}
public void start()
{
currentRunning="blue";
t1=new Thread(this,"blue");
t2=new Thread(this,"red");
t1.start();
t2.start();
}
你这是线程之间关系没处理好。假设red线程先运行,进去后开始睡眠30秒,而这时blue线程不会傻等30秒,而是也马上开始运行,假设两个线程之间只相隔了0.1秒就相继运行了,那么30.0秒后red线程先醒来,亮红灯,而30.1秒后blue线程又醒来,亮绿灯。而颜色都在g中填充,不是只亮了一个灯,而是隔得太近,绿的马上把红的盖了,你没发现!
boolean b=true;
//some code
//run方法:
public synchronized void run()
{
while(true)//红绿灯交替显示,无限循环
{
if(b) {
b=false;
try {
wait();
}
catch (InterruptedException ex) {
}
}
try
{
Thread.sleep(30000);
}
catch(InterruptedException e){} currentRunning=Thread.currentThread().getName(); repaint();//交替时重画屏幕 b=true;
notify();
}