我想在java中使用多线程概念实现交通信号。我想使用同步。这是我写的代码,但它不会按照我的期望运行:P ..我实际上做的是采用一个变量“a”,它的值决定了在特定时间应该打开哪个灯。例如:a == 0应该给红灯,然后红灯获得“a”的锁定,并在某个间隔后将值更改为== 1,然后打开到橙灯,绿灯也是如此以及..java多线程交通信号示例
代码:
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();
}
}
一个问题(与多线程无关)是Lights的每个实例都使用实例'a'字段 - 换句话说,您的三个灯中的每一个都有自己的'a',因此它们彼此独立工作。 – assylias
我如何让他们访问相同的值! – Chandeep
最简单的方法是将变量'a'设为静态 - 但这可能不是最好的解决方案。 – assylias