使用方法:
public synchronized void accessMutex() { // 锁当前对象
// access
}
public void accessMutex2() {
synchronized (this) { // 锁当前对象
// access
}
}
public static synchronized void accessMutex3() { // 锁类对象-Class
// access
}调用一个对象的wait/notify方法的前提是当前线程持有该对象的锁,
Java的每一个object都关联了一个隐藏的monitor对象,任一时刻只会有一个线程持有monitor锁,monitor对象有几个主要属性:
public class MyBlockingQueue<T> {
private Object[] data;
private int getIndex;
private int putIndex;
private int cnt;
public MyBlockingQueue(int size) {
this.data = new Object[size];
}
public synchronized void put(T item) throws InterruptedException {
while (cnt == data.length) { // 队列满,等待消费。线程唤醒后需重新检查条件是否满足
this.wait();
}
data[putIndex] = item;
putIndex = nextIndex(putIndex);
cnt++;
this.notifyAll(); // 多线程场景下需唤醒所有等待线程
}
public synchronized T get() throws InterruptedException {
while (cnt == 0) { // 队列空,等待生产。线程唤醒后需重新检查条件是否满足
this.wait();
}
Object item = data[getIndex];
getIndex = nextIndex(getIndex);
cnt--;
this.notifyAll(); // 多线程场景下需唤醒所有等待线程
return (T) item;
}
private int nextIndex(int curIndex) {
return (curIndex + 1) % data.length;
}
}这里需注意,多线程场景下
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。