Semaphore(信号量)

Semaphore(信号量)

作用

Semaphore的作用是控制并发访问的线程数目。

核心方法

//参数permits表示许可数目,即同时可以允许多少线程进行访问  
public Semaphore(int permits);
//这个多了一个参数fair表示是否是公平的,即等待时间越久的越先获取许可 
public Semaphore(int permits, boolean fair);
//获取一个许可,如果没有继续等待
public void acquire() throws InterruptedException;
//尝试获取一个许可,获取到返回true,未获取到返回false
public boolean tryAcquire();
//尝试获取指定时间内的1个许可,超时后,不再尝试获取许可,直接返回false
public boolean tryAcquire(long timeout, TimeUnit unit);
//释放一个许可
public void release();
//获取多个许可
public void acquire(int permits) throws InterruptedException;
public void acquireUninterruptibly(int permits);
//尝试获取多个许可,获取到后返回true,未获取到返回false
public boolean tryAcquire(int permits);
//尝试获取指定时间内的多个许可,超时后,不再尝试获取许可,直接返回false
public boolean tryAcquire(int permits, long timeout, TimeUnit unit) throws InterruptedException;
//释放多个许可
public void release(int permits);

示例

获取一个许可
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author scottxuan
 */
@Slf4j
public class SemaphoreExample1 {
    private final static int threadCount = 12;
    public static void main(String[] args) {
        //控制并发数目为3 (许可的总数)
        Semaphore semaphore = new Semaphore(3);
        ExecutorService executor = Executors.newCachedThreadPool();
        for (int i = 0; i < threadCount; i++) {
            final int num = i;
            executor.execute(()->{
                try {
                    //获取一个许可
                    semaphore.acquire();
                    update(num);
                    //释放一个许可
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        executor.shutdown();
    }

    private static void update(int num) throws InterruptedException {
        log.info("current num {}",num);
        //线程睡眠可以更明显的看到效果
        Thread.sleep(3000);
    }
}

//输出结果(注意时间,每次执行3个线程,间隔是设置的线程睡眠的时间3s)
//23:00:34.761 [pool-1-thread-3] INFO scottxuan.semaphore.SemaphoreExample1 - current num 2
//23:00:34.761 [pool-1-thread-2] INFO scottxuan.semaphore.SemaphoreExample1 - current num 1
//23:00:34.761 [pool-1-thread-1] INFO scottxuan.semaphore.SemaphoreExample1 - current num 0

//23:00:37.768 [pool-1-thread-6] INFO scottxuan.semaphore.SemaphoreExample1 - current num 5
//23:00:37.768 [pool-1-thread-5] INFO scottxuan.semaphore.SemaphoreExample1 - current num 4
//23:00:37.768 [pool-1-thread-4] INFO scottxuan.semaphore.SemaphoreExample1 - current num 3

//23:00:40.778 [pool-1-thread-8] INFO scottxuan.semaphore.SemaphoreExample1 - current num 7
//23:00:40.778 [pool-1-thread-9] INFO scottxuan.semaphore.SemaphoreExample1 - current num 8
//23:00:40.778 [pool-1-thread-7] INFO scottxuan.semaphore.SemaphoreExample1 - current num 6

//23:00:43.791 [pool-1-thread-10] INFO scottxuan.semaphore.SemaphoreExample1 - current num 9
//23:00:43.791 [pool-1-thread-11] INFO scottxuan.semaphore.SemaphoreExample1 - current num 10
//23:00:43.791 [pool-1-thread-12] INFO scottxuan.semaphore.SemaphoreExample1 - current num 11

获取多个许可
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author scottxuan
 */
@Slf4j
public class SemaphoreExample2 {
    private final static int threadCount = 12;
    public static void main(String[] args) {
        //控制并发量为3
        Semaphore semaphore = new Semaphore(3);
        ExecutorService executor = Executors.newCachedThreadPool();
        for (int i = 0; i < threadCount; i++) {
            final int num = i;
            executor.execute(()->{
                try {
                    //获取多个许可,这里一个线程直接获取3个,就没有了,第二个线程等他执行完释放后,才可以执行
                    semaphore.acquire(3);
                    update(num);
                    //释放多个许可
                    semaphore.release(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        executor.shutdown();
    }

    private static void update(int num) throws InterruptedException {
        log.info("current num {}",num);
        Thread.sleep(1000);
    }
}

//结果输出  注意时间  每秒,输出1次
//23:15:44.148 [pool-1-thread-1] INFO scottxuan.semaphore.SemaphoreExample2 - current num 0
//23:15:45.169 [pool-1-thread-2] INFO scottxuan.semaphore.SemaphoreExample2 - current num 1
//23:15:46.179 [pool-1-thread-3] INFO scottxuan.semaphore.SemaphoreExample2 - current num 2
//23:15:47.194 [pool-1-thread-4] INFO scottxuan.semaphore.SemaphoreExample2 - current num 3
//23:15:48.196 [pool-1-thread-5] INFO scottxuan.semaphore.SemaphoreExample2 - current num 4
//23:15:49.199 [pool-1-thread-6] INFO scottxuan.semaphore.SemaphoreExample2 - current num 5
//23:15:50.214 [pool-1-thread-7] INFO scottxuan.semaphore.SemaphoreExample2 - current num 6
//23:15:51.214 [pool-1-thread-8] INFO scottxuan.semaphore.SemaphoreExample2 - current num 7
//23:15:52.226 [pool-1-thread-9] INFO scottxuan.semaphore.SemaphoreExample2 - current num 8
//23:15:53.227 [pool-1-thread-10] INFO scottxuan.semaphore.SemaphoreExample2 - current num 9
//23:15:54.239 [pool-1-thread-11] INFO scottxuan.semaphore.SemaphoreExample2 - current num 10
//23:15:55.242 [pool-1-thread-12] INFO scottxuan.semaphore.SemaphoreExample2 - current num 11
尝试获取许可
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author scottxuan
 */
@Slf4j
public class SemaphoreExample3 {
    private final static int threadCount = 12;
    public static void main(String[] args) {
        //控制并发量为3
        Semaphore semaphore = new Semaphore(3);
        ExecutorService executor = Executors.newCachedThreadPool();
        for (int i = 0; i < threadCount; i++) {
            final int num = i;
            executor.execute(()->{
                try {
                    //尝试获取1个许可
                    if (semaphore.tryAcquire()) {
                        update(num);
                        //释放一个许可
                        semaphore.release();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        executor.shutdown();
    }

    private static void update(int num) throws InterruptedException {
        log.info("current num {}",num);
        Thread.sleep(1000);
    }
}

//输出结果 只有3个线程执行完了  3个线程获取到许可后,并发数目(许可总数)用完了 后续的线程获取不到,无法进入if中的代码
//23:17:35.375 [pool-1-thread-1] INFO scottxuan.semaphore.SemaphoreExample3 - current num 0
//23:17:35.375 [pool-1-thread-2] INFO scottxuan.semaphore.SemaphoreExample3 - current num 1
//23:17:35.375 [pool-1-thread-3] INFO scottxuan.semaphore.SemaphoreExample3 - current num 2
尝试获取带时间参数的许可
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author scottxuan
 */
@Slf4j
public class SemaphoreExample4 {
    private final static int threadCount = 12;
    public static void main(String[] args) {
        //控制并发量为3(许可总数)
        Semaphore semaphore = new Semaphore(3);
        ExecutorService executor = Executors.newCachedThreadPool();
        for (int i = 0; i < threadCount; i++) {
            final int num = i;
            executor.execute(()->{
                try {
                    //尝试获取3s内的许可,获取不到则返回false
                    if (semaphore.tryAcquire(3, TimeUnit.SECONDS)) {
                        update(num);
                        //释放一个许可
                        semaphore.release();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        executor.shutdown();
    }

    private static void update(int num) throws InterruptedException {
        log.info("current num {}",num);
        Thread.sleep(1000);
    }
}

//输出结果
//总计12个线程,并发为3,线程执行沉睡1s,所以每次执行3个线程,在第3次执行完成后,线程的睡眠总时间也到达3s了,
//尝试获取指定时间内的许可失败后,直接返回false
//23:25:11.166 [pool-1-thread-2] INFO scottxuan.semaphore.SemaphoreExample4 - current num 1
//23:25:11.166 [pool-1-thread-3] INFO scottxuan.semaphore.SemaphoreExample4 - current num 2
//23:25:11.166 [pool-1-thread-1] INFO scottxuan.semaphore.SemaphoreExample4 - current num 0

//23:25:12.176 [pool-1-thread-5] INFO scottxuan.semaphore.SemaphoreExample4 - current num 4
//23:25:12.176 [pool-1-thread-6] INFO scottxuan.semaphore.SemaphoreExample4 - current num 5
//23:25:12.176 [pool-1-thread-4] INFO scottxuan.semaphore.SemaphoreExample4 - current num 3

//23:25:13.187 [pool-1-thread-7] INFO scottxuan.semaphore.SemaphoreExample4 - current num 6
//23:25:13.187 [pool-1-thread-8] INFO scottxuan.semaphore.SemaphoreExample4 - current num 7
//23:25:13.187 [pool-1-thread-9] INFO scottxuan.semaphore.SemaphoreExample4 - current num 8
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Windows系统信号量Semaphore)是一种同步对象,用于在多个线程之间协调共享资源的访问。Windows提供了一组API函数来创建、操作和销毁信号量。 以下是一些与信号量相关的API函数: 1. CreateSemaphore:创建一个信号量对象。 2. WaitForSingleObject:等待一个信号量对象。 3. ReleaseSemaphore:释放一个信号量对象。 4. OpenSemaphore:打开一个已经存在的信号量对象。 5. CloseHandle:关闭一个信号量对象的句柄。 下面是一个使用信号量的示例: ```C++ #include <windows.h> #include <iostream> using namespace std; HANDLE hSemaphore; // 信号量句柄 DWORD WINAPI ThreadProc(LPVOID lpParam) { // 等待信号量 WaitForSingleObject(hSemaphore, INFINITE); // 访问共享资源 cout << "Thread " << GetCurrentThreadId() << " access shared resource." << endl; // 释放信号量 ReleaseSemaphore(hSemaphore, 1, NULL); return 0; } int main() { // 创建信号量 hSemaphore = CreateSemaphore(NULL, 1, 1, NULL); // 创建线程 HANDLE hThread1 = CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL); HANDLE hThread2 = CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL); // 等待线程结束 WaitForSingleObject(hThread1, INFINITE); WaitForSingleObject(hThread2, INFINITE); // 关闭信号量句柄 CloseHandle(hSemaphore); return 0; } ``` 在这个示例,我们创建了一个信号量句柄,并创建了两个线程。线程会等待信号量,然后访问共享资源。访问完成后,线程会释放信号量。由于信号量的初始计数为1,所以只有一个线程能够访问共享资源。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值