(1)tryLock()方法:尝试锁,如果无法获取锁标记,返回false;如果获取了锁标记,返回true。
(2)tryLock(long time, TimeUnit unit):阻塞尝试锁。参数代表时长,在指定时长内尝试锁。
(3)unlock():如果没有获取锁标记就放锁,会抛出异常。
(4)lockInterruptibly():获取锁,如果锁可用则线程继续执行;如果锁不可用则线程进入阻塞状态,此时可以在其它线程执行时调用这个线程的interrupt方法打断它的阻塞状态。
示例一:
public class Test2 {
Lock lock = new ReentrantLock();
public void m1() {
try {
lock.lock();// 加锁
for (int i = 0; i < 10; i++) {
TimeUnit.SECONDS.sleep(1);
System.out.println("public void m1()" + i);
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();// 解锁
}
}
public void m2() {
boolean isLocked = false;
try {
// 尝试锁,如果无法获取锁标记,返回false;如果获取了锁标记,返回true
// isLocked = lock.tryLock();
// 阻塞尝试锁
// 参数代表时长,在指定时长内尝试锁
isLocked = lock.tryLock(5, TimeUnit.SECONDS);
if (isLocked) {
System.out.println("public void m2() synchronized");
} else {
System.out.println("public void m2() unsynchronized");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (isLocked) {
// 先判断是否获取了锁标记。如果获取了锁标记,放锁
// 如果没有获取锁标记就放锁,会抛出异常
lock.unlock();
}
}
}
public static void main(String[] args) {
Test2 t = new Test2();
new Thread(new Runnable() {
public void run() {
t.m1();
}
}).start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(new Runnable() {
public void run() {
t.m2();
}
}).start();
}
}
示例二:
public class Test3 {
Lock lock = new ReentrantLock();
public void m1() {
try {
lock.lock();
for (int i = 0; i < 5; i++) {
TimeUnit.SECONDS.sleep(1);
System.out.println("public void m1()" + i);
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void m2() {
try {
// 等待锁,线程进入阻塞状态
// 可以在其它线程执行时调用这个线程的interrupt方法打断它的阻塞状态
lock.lockInterruptibly();
System.out.println("public void m2()");
} catch (InterruptedException e) {
System.out.println("public void m2() interrupted");
} finally {
try {
lock.unlock();// 如果阻塞状态被打断,因为没有获取锁标记就放锁,会抛出异常
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
final Test3 t = new Test3();
new Thread(new Runnable() {
public void run() {
t.m1();
}
}).start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread t2 = new Thread(new Runnable() {
public void run() {
t.m2();
}
});
t2.start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.interrupt();// 打断t2线程的阻塞状态
}
}
网友评论