活跃农民
- 积分
- 519
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-9-11
- 最后登录
- 1970-1-1
|
感谢楼主分享,第二题followup是说把程序改为线程安全的么,直接简单的加锁可以么?因为多线程不是很懂,写了一个不知道对不对,希望能给指点一下
- public class ImpQueue {
- private int[] queue;
- private int curSize = 0;
- private int size;
- private int head = 0;
- private int tail = 0;
-
- public ImpQueue(int size) {
- queue = new int[size];
- this.size = size;
- }
-
- public void offer(int value) throws Exception {
- synchronized(this) {
- if (curSize != size) {
- queue[head] = value;
- curSize++;
- head++;
- if (head == size) {
- head = 0;
- }
- return;
- }
- throw new Exception("Queue is full");
- }
- }
-
- public int poll() throws Exception{
- synchronized (this) {
- if (curSize != 0) {
- int output = queue[tail];
- curSize--;
- Thread.sleep(100);
- tail++;
- if (tail == size) {
- tail = 0;
- }
- return output;
- }
- throw new Exception("Queue is empty");
- }
- }
- }
复制代码 |
|