java java多线程交通信号示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14012826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java multi threading traffic signal example
提问by Chandeep
I am trying to implement traffic signal in java using multi threading concepts. I want to use synchronization. This is code i have written but it doesn't run according to my expectations :P .. What i am actually doing is taking a variable "a" whose value determines which light should be on at a particular time. For eg: a==0 should give red light.. then red light acquires a lock on "a" and changes the value to a==1 after some interval and then switches on to orange light and the same happens for green light as well ..
我正在尝试使用多线程概念在 java 中实现交通信号。我想使用同步。这是我写的代码,但它没有按照我的期望运行 :P .. 我实际上在做的是取一个变量“a”,它的值决定了在特定时间应该打开哪个灯。例如:a==0 应该发出红光.. 然后红光获得对“a”的锁定,并在一段时间后将值更改为 a==1,然后打开橙光,绿光也发生同样的情况好 ..
Code:
代码:
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();
}
}
}
}
}
Main Class:
主要类:
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();
}
}
回答by Patricia Shanahan
synchronized(this) is not very useful when you have several different instances of the class. Only block that are synchronized on the same object are prevented from running in parallel.
当您有几个不同的类实例时,synchronized(this) 不是很有用。只有在同一对象上同步的块才会被阻止并行运行。
One option would be to pass a common object, perhaps containing the "a" you want them to use, to the Lights constructor and have the threads synchronize on that object.
一种选择是将一个公共对象(可能包含您希望它们使用的“a”)传递给 Lights 构造函数,并使线程在该对象上同步。