第四课:Linkedin 专题之多线程

点击文档

回家作业是下面2道:

请回帖发一下你的答案代码

有三个问题,X老师给的代码用lock而不用synchronized实现的这里

public void push(E obj) throws Exception {
		this.pushLock.lock();
		this.lock.lock();
		try {
			while (this.capacity == this.queue.size()) {
				this.notFull.wait();
			}
			this.queue.add(obj);
			this.notEmpty.notifyAll();
		} finally {
			this.lock.unlock();
			this.pushLock.lock();
		}
}
  1. 为什么要多用一个pushLock?
  2. 最后在finally里的pushLock是不是应该unlock?这里写错了?
  3. 为什么this.queue不用volatile?如果每个thread有自己的local queue copy,即使别的thread更新了queue,当前thread也不会看到啊?

这个相当于读写锁的类似机制。push lock 是防止方法 push 和 pushList 之间的互相竞争

应该是写错了,应该是unlock

这里你对内存的理解和掌握不到位了。this.queue是一个指针,指向 heap 上的 allocated memory,即真正的queue。queue 变大变小,指针并没有变。

这个assertion 是错误的,每个thread 都是拿着那个指针,指向同一个 heap 上的queue。