Semaphore 信号量,就是一个允许实现设置好的令牌。也许有1个,也许有10个或更多。
谁拿到令牌(acquire)就可以去执行了,如果没有令牌则需要等待。
执行完毕,一定要归还(release)令牌,否则令牌会被很快用光,别的线程就无法获得令牌而执行下去了。
请仔细体会里面关于仓库的处理,
1 是如何保证入库时,如果仓库满就等待,
2 出库时,如果仓库无货就等待的。
3 以及对仓库只有10个库位的处理。
4 对同步问题的处理。
package com.test.current;
import java.util.concurrent.Semaphore;
public class TestSemaphore {
public static void main(String[] args) {
for (int i = 0; i <= 3; i++) {
new Thread(new Producer()).start();
new Thread(new Consumer()).start();
}
}
//仓库
static WareHouse buffer = new WareHouse();
//生产者
static class Producer implements Runnable{
static int num = 1;
public void run() {
int n = num++;
while(true){
try{
buffer.put(n);
System.out.println(">"+n);
Thread.sleep(10);
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class Consumer implements Runnable{
public void run() {
while (true) {
try {
System.out.println("<"+buffer.take());
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class WareHouse{
//非满锁
final Semaphore notFull = new Semaphore(10);
//非空锁
final Semaphore notEmpty = new Semaphore(0);
//互斥锁
final Semaphore mutex = new Semaphore(1);
//库存容量
final Object[] items = new Object[10];
int putPosi, takePosi, count;
public void put(Object x)throws InterruptedException{
try{
notFull.acquire();
mutex.acquire();
items[putPosi] = x;
if (++putPosi == items.length) {
putPosi = 0;
}
count++;
}finally{
notEmpty.release();
mutex.release();
}
}
public Object take()throws InterruptedException{
notEmpty.acquire();
mutex.acquire();
try{
Object x = items[takePosi];
if(++takePosi == items.length){
takePosi = 0;
}
--count;
return x;
}finally{
notFull.release();
mutex.release();
}
}
}
}