天天看点

JUC之Semaphore-多线程与高并发

我们学习锁的时候,当一个线程获取到锁,它才可以正常执行;未获得锁的线程阻塞。而Semaphore也相当于锁,不过它可以定义锁的数量,即同一时间可以控制让多个线程都获得锁从而正常运行。

它控制同一时间点并发执行线程的个数。也可以控制某个资源可被同时访问的个数。主要用于限流。

用法就是一个acquire()方法用于获得锁,如果没有获得锁则线程阻塞;另一个方法就是release()方法,线程执行完成后释放锁。

初始化时可以传参指定控制并发的数量即锁的数量。

Semaphore s = new Semaphore(2);
           
package com.mashibing.juc.c_020;

import java.util.concurrent.Semaphore;

public class T11_TestSemaphore {
    public static void main(String[] args) {
        //Semaphore s = new Semaphore(2);
        Semaphore s = new Semaphore(2, true);
        //允许一个线程同时执行
        //Semaphore s = new Semaphore(1);

        new Thread(()->{
            try {
                s.acquire();

                System.out.println("T1 running...");
                Thread.sleep(200);
                System.out.println("T1 running...");

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                s.release();
            }
        }).start();

        new Thread(()->{
            try {
                s.acquire();

                System.out.println("T2 running...");
                Thread.sleep(200);
                System.out.println("T2 running...");

                s.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}