public class TestLock implements Lock {
private Object lock = new Object();
private long owner = -1;
@Override
public void lock() {
while(owner != -1){
System.out.println(Thread.currentThread().getId() + "等待锁");
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
owner = Thread.currentThread().getId();
System.out.println(owner + "获取到锁");
}
@Override
public void unlock() {
synchronized (lock){
System.out.println(owner + "释放锁");
lock.notify();
owner = -1;
}
}
public static void main(String[] args) throws InterruptedException {
TestLock lock = new TestLock();
for (int i = 0; i < 100; i++) {
new Thread(() ->{
lock.lock();
try {
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + "执行");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}).start();
}
TimeUnit.HOURS.sleep(1);
}
public static int incre(int num){
return num++;
}
@Override
public void lockInterruptibly() throws InterruptedException {
}
@Override
public boolean tryLock() {
return false;
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return false;
}
@Override
public Condition newCondition() {
return null;
}
}
使用synchronized实现Lock接口的lock和unlock方法
于 2021-06-09 17:51:20 首次发布