目录
- Semaphore
- 例子代码和输出
- semaphore.acquire();
- semaphore.release();
Semaphore
semaphore :
英[ˈseməfɔː(r)] 美[ˈseməfɔːr]
n. 旗语; 信号标;
v. 打旗语; (用其他类似的信号系统)发信号;
[例句]Semaphore was widely used at sea, before the advent of electricity.
在电问世以前,旗语在海上运用广泛。
[其他] 第三人称单数:semaphores 复数:semaphores 现在分词:semaphoring 过去式:semaphored 过去分词:semaphored
例子代码和输出
public class Test {final static int CNT = 2;static Semaphore semaphore = new Semaphore(CNT);public static void main(String[] args) throws InterruptedException {Runnable runnable = () -> {try {semaphore.acquire();// 业务处理TimeUnit.SECONDS.sleep(2);System.out.println(Thread.currentThread().getName() + ":" + " finished");} catch (Exception e) {e.printStackTrace();} finally {System.out.println(Thread.currentThread().getName() + ":" + " release");semaphore.release();}};List<Thread> threads = new ArrayList<>(4);for(int i= 0;i<6;i++) {Thread thread = new Thread(runnable);threads.add(thread);}for(Thread thread: threads){thread.start();}}
}
输入如下:可以看到同时最多只有2个线程能得到执行
semaphore.acquire();
CAS操作消耗一个信号量;如果没有信号量可消耗了,就死循环等待了
semaphore.release();
semaphore.acquire()的反向操作。
release增加信号量;acquire减少信号量。