如果多个线程试图锁定,信号量如何表现

时间:2015-10-05 16:06:49

标签: java multithreading

我试图了解信号量,并且知道信号量保持一组许可或允许的锁数,但我仍然有很多疑问。

是否为每个类或整个类的实例维护了允许的锁数?

我的意思是说根据我的代码将信号量限制为2时,4个线程如何获得锁定。

这是否意味着每个类的实例都会保留许可。如果是, 那么它不会在代码状态中产生不一致吗?

在运行下面的代码时,输​​出如下:

t1 having ts1 acqired lock
t2 having ts2 acqired lock
t3 having ts1 acqired lock
t4 having ts2 acqired lock
t1 having ts1 released lock
t4 having ts2 released lock
t3 having ts1 released lock
t2 having ts2 released lock

代码:

public class SemaphoreTest {


    public static void main(String[] args) {
        Task ts1=new Task();
        Task ts2=new Task();
        Thread t1=new Thread(ts1,"t1 having ts1");
        Thread t2=new Thread(ts2,"t2 having ts2");
        Thread t3=new Thread(ts1,"t3 having ts1");
        Thread t4=new Thread(ts2,"t4 having ts2");
        t1.start();
        t3.start();
        t2.start();
        t4.start();

    }
}

class Task implements Runnable{
    Semaphore noOfLocks=new Semaphore(2);

    @Override
    public void run() {
        try {
            noOfLocks.acquire();
            System.out.println(Thread.currentThread().getName() +" acqired lock");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
            noOfLocks.release();
            System.out.println(Thread.currentThread().getName() +" released lock");
        }

    }

}

1 个答案:

答案 0 :(得分:4)

Task类的每个实例都有自己的Semaphore实例。

class Task implements Runnable {
    Semaphore noOfLocks=new Semaphore(2);
    ...

每个信号量实例都有自己的许可证计数器。

您创建了两个Task个实例,因此您有2个Semaphore个实例,每个实例最初有2个许可。

    Task ts1=new Task();
    Task ts2=new Task();

同时在多个线程中执行ts1将导致线程争用同一个信号量。与在多个线程中执行ts2一样。在你的代码中:

    Thread t1=new Thread(ts1,"t1 having ts1");
    Thread t3=new Thread(ts1,"t3 having ts1");

    Thread t2=new Thread(ts2,"t2 having ts2");
    Thread t4=new Thread(ts2,"t4 having ts2");

所以最后有2个线程使用2个允许时间中的2个2.没有什么需要等待许可证,因为每个人都有足够的。

如果您想查看某些内容,请使用现有任务制作更多主题,或减少初始许可数量。