java多线程流量信号示例

时间:2012-12-23 16:58:41

标签: java multithreading thread-synchronization

我正在尝试使用多线程概念在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();


}
}

1 个答案:

答案 0 :(得分:1)

当你有几个不同的类实例时,

synchronized(this)不是很有用。仅阻止在同一对象上同步的块并行运行。

一种选择是将一个公共对象(可能包含您希望它们使用的“a”)传递给Lights构造函数,并让线程在该对象上同步。

相关问题