Semaphore

一个类说明Java 信号量 Semaphore 的用法

星期五, 四月 10th, 2015 | JAVA-and-J2EE | 没有评论

在用Semaphore 信号量的时候,感觉对公平调度比较有用,可以控制多线程争夺资源时候,最大可以几个在执行,随手写了代码测试下,如下:
说明: 1. acquire() 获取一个许可,如果没有就等待
2. release() 释放一个许可
3. Semaphore可以控制某个资源可被同时访问的个数,自行初始化的数量,为1当然就顺序执行了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.i5a6.semp.test;
 
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
 
public class SemaphoreTest {
 
	private Semaphore semp;
 
	private ExecutorService executorPool;
 
	public SemaphoreTest(int threadNum) {
		semp = new Semaphore(threadNum);
		executorPool = Executors.newFixedThreadPool(threadNum);
	}
 
	public void doEnd() {
		this.executorPool.shutdown();
	}
 
	public void doMsg(int num) {
		try {
			semp.acquire();
			executorPool.execute(new HelloUExecutor(num));
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
 
	class HelloUExecutor implements Runnable {
		private int num;
 
		public HelloUExecutor(int num) {
			this.num = num;
		}
 
		Random r = new Random();
 
		@Override
		public void run() {
			try {
				System.out.println(num);
				Thread.sleep(r.nextInt(1000));
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				semp.release();
			}
		}
	}
 
	public static void main(String[] args) {
		// 初始化为1 顺序执行
		SemaphoreTest st = new SemaphoreTest(5);
		for (int i = 0; i < 20; i++) {
			st.doMsg(i);
		}
		st.doEnd();
	}
 
}

Tags: ,

Search

文章分类

Links

Meta