y*****e 发帖数: 712 | 1 好怕这种thread safe的题,不知有人愿意分享一下代码吗?在网上找了几个代码,因
为半懂不懂的,也分不出个好坏高低来,还是觉得板上牛人多。
http://codereview.stackexchange.com/questions/7002/java-blockin |
y*****e 发帖数: 712 | 2 public class BQueue {
private Queue q = new LinkedList();
private int limit;
public BQueue(int limit) {
this.limit = limit;
}
public synchronized void put (T t) throws InterruptedException {
while (isFull()) {
wait();
}
boolean e = isEmpty();
q.add(t);
if (e)
notifyAll();
}
public synchronized T get () throws InterruptedException {
while (isEmpty()) {
wait();
}
boolean f = isFull();
T t = q.poll();
if (f)
notifyAll();
return t;
}
private boolean isEmpty() {
return q.size() == 0;
}
private boolean isFull() {
return q.size() == limit;
}
}
这个implemetation里为啥boolean e = isEmpty()要在q.add(t)前面?如果empty,但
add之后不就不再empty了吗?这时候再notifyAll还有效吗? |
e***a 发帖数: 1661 | 3 there is some math theory in it |
f******n 发帖数: 198 | 4 都让你写这个了,怎么可能还让你用synchronized,肯定会让你直接用lock看你知不知
道什么时候可以context switch,什么时候不可以。
【在 y*****e 的大作中提到】 : public class BQueue { : private Queue q = new LinkedList(); : private int limit; : public BQueue(int limit) { : this.limit = limit; : } : public synchronized void put (T t) throws InterruptedException { : while (isFull()) { : wait(); : }
|
y*****e 发帖数: 712 | 5 T_T
我再去找找用lock怎么写。。。
【在 f******n 的大作中提到】 : 都让你写这个了,怎么可能还让你用synchronized,肯定会让你直接用lock看你知不知 : 道什么时候可以context switch,什么时候不可以。 : :
|
c******f 发帖数: 243 | 6 可以用这个吗
projectlombok dot org/features/Synchronized dot html |
D**C 发帖数: 6754 | 7 这都没法编译,wait/notify都要建立在一个object上面。
当然略加修改就可以了,我不觉得还需要check empty/full,只需要notify the
waiting process就可以了,没有waiting的,notifyall没有负效果
【在 y*****e 的大作中提到】 : public class BQueue { : private Queue q = new LinkedList(); : private int limit; : public BQueue(int limit) { : this.limit = limit; : } : public synchronized void put (T t) throws InterruptedException { : while (isFull()) { : wait(); : }
|
b**********5 发帖数: 7881 | 8 小姐啊, 有个网站叫grepcode, 你自己去看看java的blockingqueue的source code不
就知道了?
【在 y*****e 的大作中提到】 : 好怕这种thread safe的题,不知有人愿意分享一下代码吗?在网上找了几个代码,因 : 为半懂不懂的,也分不出个好坏高低来,还是觉得板上牛人多。 : http://codereview.stackexchange.com/questions/7002/java-blockin
|