我正在尝试使用多线程概念在 java 中实现交通信号。我想使用同步。这是我编写的代码,但它没有按照我的期望运行:P .. 我实际上正在做的是取一个变量“a”,它的值决定了在特定时间应该打开哪个灯。例如:a==0 应该发出红灯.. 然后红灯在“a”上获得锁定,并在一段时间后将值更改为 a==1,然后打开橙灯,绿灯也会发生同样的情况出色地 ..
代码:
package test;
class Lights implements Runnable {
int a=0,i,j=25;
synchronized public void valueA()
{
a=a+1;
}
public void showLight()
{
System.out.println("The Light is "+ Thread.currentThread().getName());
}
@Override
public void run() {
// TODO Auto-generated method stub
for(i=25;i>=0;i--)
{
while(j<=i&&j>=10&&a==0)
{
showLight();
/*some code here that locks the value of "a" for thread 1
and keeps it until thread 1 unlocks it! */
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
j--;
}
while(j<10&&j>=5&&a==1)
{
showLight();
/*some code here that locks the value of "a" for thread 1
and keeps it until thread 1 unlocks it! */
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
j--;
}
while(j<5&&j>=0&&a==2)
{
showLight();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
主类:
package test;
public class MainTraffic {
public static void main(String args[])
{
Runnable lights=new Lights();
Thread one=new Thread(lights);
Thread two=new Thread(lights);
Thread three=new Thread(lights);
one.setName("red");
two.setName("orange");
three.setName("green");
one.start();
two.start();
three.start();
}
}