我有LinkedBlockingQueue
,还有一些操作它的线程。
public void run(){
...
foo(linkedBlockingQueue.take());
...
}
public void foo(Object o){
synchronized(o){
//operate on the object
....
//after operate re-insert the object inside the queue
}
}
如果我有这种情况:
一个包含5个元素的阻塞队列和#34;最幸运的"线程已经获得了第一个元素的控制权:
wait
?。synchronized
块是没用的吗?mutex exclusion
的情况下插入此元素吗?提前感谢。
答案 0 :(得分:3)
一个包含5个元素的阻塞队列,并获得了“最幸运”的线程 控制第一个元素:
other threads that concurrently wanted the first element will put in wait?.
不,其他线程将获得第二个,第三个等元素,直到队列为空。只有在这种情况下,它们才会阻止。
it is useless to use a synchronized block if the first sentence is right?
这个问题的答案与第一个问题的答案无关。如果你在一个线程中处理被采用的对象或者是不可变的,那么是的,不需要同步,但是否则你可能需要它。
其他线程可以在拾取时间隔内访问其他位置 没有互斥的第一个元素和插入 排斥?
您在询问其他线程是否可能从队列中获取更多元素,直到重新添加第一个元素为止?是的,队列未锁定,可以从其他线程访问。