信号量公平性设定

时间:2017-09-16 09:42:16

标签: java multithreading

我正在尝试理解Semaphore的公平性设置(int num,boolean how)。 我有这个程序。公平性设置似乎无效。

public static void main(String[] args) throws InterruptedException {


        shared sh=new shared();
        Semaphore sm=new Semaphore(1,true);
        newthread1 nh1=new  newthread1(sm,sh,"nh1");

        newthread1 nh3=new newthread1(sm, sh,"nh3");
        newthread1 nh2=new newthread1(sm, sh,"nh2");
        }
}



Class shared:-

public class shared {

    public void msg()
    {
        for(int i=65;i<68;i++) {
            System.out.println(Thread.currentThread().getName()+ " " + (char)i);

        }
    }

}

    class new thread:-
import java.util.concurrent.*;
public class newthread1 implements Runnable  {
    shared sh=null;
    Semaphore sem=null;
    Thread t=null;
    String name=null;
    public newthread1(Semaphore sem,shared sh,String name) {
        // TODO Auto-generated constructor stub
        this.sem=sem;
        this.sh=sh;
        this.name=name;

        t=new Thread(this,name);
        t.start();
    }

    @Override
    public void run() {

        try {
            sem.acquire();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName() +" has accuqired the lock");
        sh.msg();

        sem.release();
        // TODO Auto-generated method stub

    }
    } 

请在此纠正我的理解: - 我的理解是等待线程应该获得锁定,他们请求锁定的顺序。如果我运行程序,它不会给我正确的结果。 每次给出不同的结果。

谢谢

1 个答案:

答案 0 :(得分:0)

您可能认为启动线程的顺序很重要。它不是。重要的是哪个线程首先到达sem.acquire()来电。

Semaphore的公平性设置在这里没什么用。