【发布时间】:2015-06-21 12:12:32
【问题描述】:
如果我只是做这样的事情:
synchronized(taskQueue) { //taskQueue is a BlockingQueue
taskQueue.drainTo(tasks); //tasks is a list
}
我确定不能在同步块内执行对taskQueue.put() 和taskQueue.take() 的并发调用吗?
换句话说,我是否让 drainTo() 方法成为原子方法?
或者更一般地说,我如何使线程安全操作的组合原子化?
例子:
if(taskQueue.size() == 1) {
/*Do a lot of things here, but I do not want other threads
to change the size of the queue here with take or put*/
}
//taskQueue.size() must still be equal to 1
【问题讨论】:
标签: java multithreading synchronization