Semaphore两个重要的方法就是
semaphore.acquire() 请求一个信号量,这时候的信号量个数-1(一旦没有可使用的信号量,也即信号量个数变为负数时,再次请求的时候就会阻塞,直到其他线程释放了信号量)
semaphore.release() 释放一个信号量,此时信号量个数+1
-
public
class SemaphoreTest {
-
private Semaphore mSemaphore =
new Semaphore(
5);
-
public void run(){
-
for(
int i=
0; i<
100; i++){
-
new Thread(
new Runnable() {
-
@Override
-
public void run() {
-
test();
-
}
-
}).start();
-
}
-
}
-
-
private void test(){
-
try {
-
mSemaphore.acquire();
-
}
catch (InterruptedException e) {
-
e.printStackTrace();
-
}
-
System.out.println(Thread.currentThread().getName() +
" 进来了");
-
try {
-
Thread.sleep(
1000);
-
}
catch (InterruptedException e) {
-
e.printStackTrace();
-
}
-
System.out.println(Thread.currentThread().getName() +
" 出去了");
-
mSemaphore.release();
-
}
-
}
示例中实例化了具有5个信号量的semaphore,保证只有5个线程在执行test方法
-
04-
18
17:
05:
46.350
14192-
14228/com.tongxt.myapplication I/System.out: Thread-
1228 进来了
-
04-
18
17:
05:
46.351
14192-
14231/com.tongxt.myapplication I/System.out: Thread-
1231 进来了
-
04-
18
17:
05:
46.354
14192-
14233/com.tongxt.myapplication I/System.out: Thread-
1233 进来了
-
04-
18
17:
05:
46.354
14192-
14232/com.tongxt.myapplication I/System.out: Thread-
1232 进来了
-
04-
18
17:
05:
46.355
14192-
14234/com.tongxt.myapplication I/System.out: Thread-
1234 进来了
-
-
04-
18
17:
05:
47.351
14192-
14228/com.tongxt.myapplication I/System.out: Thread-
1228 出去了
-
04-
18
17:
05:
47.351
14192-
14236/com.tongxt.myapplication I/System.out: Thread-
1236 进来了
-
04-
18
17:
05:
47.352
14192-
14231/com.tongxt.myapplication I/System.out: Thread-
1231 出去了
-
04-
18
17:
05:
47.352
14192-
14235/com.tongxt.myapplication I/System.out: Thread-
1235 进来了
-
04-
18
17:
05:
47.354
14192-
14233/com.tongxt.myapplication I/System.out: Thread-
1233 出去了
-
04-
18
17:
05:
47.354
14192-
14237/com.tongxt.myapplication I/System.out: Thread-
1237 进来了
-
04-
18
17:
05:
47.354
14192-
14232/com.tongxt.myapplication I/System.out: Thread-
1232 出去了
-
04-
18
17:
05:
47.354
14192-
14229/com.tongxt.myapplication I/System.out: Thread-
1229 进来了
-
04-
18
17:
05:
47.356
14192-
14234/com.tongxt.myapplication I/System.out: Thread-
1234 出去了
-
04-
18
17:
05:
47.356
14192-
14230/com.tongxt.myapplication I/System.out: Thread-
1230 进来了
-
04-
18
17:
05:
48.351
14192-
14236/com.tongxt.myapplication I/System.out: Thread-
1236 出去了