/**
* 用synchronized实现lock锁
*/
public class MyLock {
private final static long NONE = -1;
private long owner = NONE;
public synchronized void lock(){
long currentThreadId = Thread.currentThread().getId();
if(owner==currentThreadId){
System.out.println("Thread is has lock");
}
while(owner!=NONE){
try{
System.out.println(String.format("%s want to lock",currentThreadId));
wait();
}catch (Exception e){
e.printStackTrace();
}
}
owner=currentThreadId;
System.out.println(String.format("%s get lock",currentThreadId));
}
public synchronized void unlock(){
long currentThreadId = Thread.currentThread().getId();
if(owner!=currentThreadId){
System.out.println("Only lock owner can unlock the lock");
}
System.out.println(String.format("thread %s is unlocking", owner));
owner=NONE;
notify();
}
public static void main(String[] args) {
MyLock lock = new MyLock();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
lock.lock();
System.out.println(String.format("thread %s is running...", Thread.currentThread().getId()));
try{
Thread.sleep(3000);
}catch (Exception e){
e.printStackTrace();
}
lock.unlock();
}
});
Thread thread2 = new Thread(new Thread(new Runnable() {
@Override
public void run() {
lock.lock();
System.out.println(String.format("thread %s is running...", Thread.currentThread().getId()));
try{
Thread.sleep(3000);
}catch (Exception e){
e.printStackTrace();
}
lock.unlock();
}
}));
thread1.start();
thread2.start();
}
}
运行结果如下
11 get lock
13 want to lock
thread 11 is running...
thread 11 is unlocking
13 get lock
thread 13 is running...
thread 13 is unlocking