初学者流泪泣问(想了一天也想不出阿,555555)
东西方向,南北方向各一个交通灯
我想让南北向交通灯绿色延迟5秒钟跳成黄色,再延迟1秒钟,跳成红色
此时进入东西线程的交通灯,东西方向的灯由红跳成绿让绿色延迟5秒钟跳成黄色,再延迟1秒钟,跳成红色
不断循环
可是当我用sleep时(让东西方向绿灯延迟时,会跳到南北方向上运行,乱套了),谁帮我该该程序阿,谢了!
--------------------------------------------------------------------------
class TrafficLight implements Runnable
{
private String position;
private String str=new String(" ");
private boolean startdemo=true;
private final int red=0;
private final int yellow=1;
private final int green=2;
private void getout(int x)
{
switch (x)
{
case 0:
System.out.println("the trafficlight on "+position+" is red!");
break;
case 1:
System.out.println("the trafficlight on "+position+"is yellow!");
break;
case 2:
System.out.println("the trafficlight on "+position+" is green!");
break;
}
}
private void hold(int x)
{
try
{
Thread.sleep(x);
}
catch(Exception e){}
}
public TrafficLight(String x)
{
position=x;
}
public void run()
{
while(startdemo)
{
synchronized(str)
{
getout(green);
hold(3000);
getout(yellow);
hold(1000);
getout(red);
}
}
}
}
public class TrafficDemo
{
public static void main(String args[])
{
TrafficLight a=new TrafficLight("southnorth");
TrafficLight b=new TrafficLight("eastwest");
Thread t1=new Thread(a);
Thread t2=new Thread(b);
t1.start();
t2.start();
}
}