一、为什么1.5后会引入Concurrent包
其实应该这样说 Synchronized 有什么局限性:
- 不能一处加锁,另一处释放;
- 没有超时机制;
- 没有公平机制;
- 没有读写功能;
- 。。。
- 严格的块结构
- 活跃性问题
- 改变锁的语义:重入性、读写保护、公平性
- 访问控制
二、Java原生提供的锁工具有哪些
- Synchronized
- Object.wait()
- Object.notify()
- Object.notifyAll()
PS:JavaSynchronized是基于每线程而不是没调用
三、提供超时锁获取方式
/**
* Created by xiejisheng on 18/5/31.
*/
public class Mutex {
// JMM保证boolean语义的完整性,不保证可见性
private volatile boolean inuse = false;
public void acquire() throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
synchronized (this) {
try {
while (inuse)
wait();
inuse = true;
} catch (InterruptedException e) {
notify();
throw e;
}
}
}
public synchronized void release() {
inuse = false;
notify();
}
public boolean tryAcquire() throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
synchronized (this) {
if (inuse)
return false;
else {
inuse = true;
notify();
return true;
}
}
}
public boolean tryAcquire(long msecs) throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
synchronized (this) {
if (!inuse) {
inuse = true;
return true;
} else if (msecs <= 0) {
return false;
} else {
long waitTime = msecs;
long start = System.currentTimeMillis();
try {
for (; ; ) {
wait(waitTime);
if (!inuse) {
inuse = true;
return true;
} else {
long end = System.currentTimeMillis();
waitTime = msecs - (end - start);
if (waitTime <= 0)
return false;
}
}
} catch (InterruptedException ex) {
notify();
throw ex;
}
}
}
}
}
四、分析及问题
下一节会阐述Java原生锁工具的原理。
正确的道路就那么几条,而错误的方式千奇百怪,在编程的世界尤其如此。有时候你会不禁自问,什么样的奇葩竟会写出这么反人类的代码。