import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; public class ReentrantLockTest { public static ReentrantLock reenT = new ReentrantLock(); // Parameter defaultfalseUnfair lock public static voidtest2() throws Exception{
Thread t0 = new Thread(() -> {
if (reenT.tryLock()) {
System.out.println(Thread.currentThread().getName() + "Got the lock.");
reenT.lock();
System.out.println(Thread.currentThread().getName() + "Got the lock.");
reenT.unlock();
System.out.println(Thread.currentThread().getName() + "Release the lock.");
reenT.unlock();
System.out.println(Thread.currentThread().getName() + "Release the lock."); }}); Thread t1 = new Thread(() -> {if (reenT.tryLock()) {
System.out.println(Thread.currentThread().getName() + "Got the lock."); reenT.unlock(); }}); Thread t2 = new Thread(() -> { reenT.lock(); System.out.println(Thread.currentThread().getName() +"Got the lock.");
reenT.unlock();
});
t0.start();
t1.start();
t2.start();
Thread.sleep(2000L);
System.out.println("Thread t0:" + t0.getState().toString());
System.out.println("Thread T1:" + t1.getState().toString());
System.out.println("Thread T2:" + t2.getState().toString());
}
public static void main(String[] args) {
try {
test(2); } catch (Exception e) { e.printStackTrace(); }}} > Thread won the Thread lock 0-0 won the Thread lock - 0 released the Thread lock - zero release the Thread lock - 2 won the Thread lock t0: TERMINATED threads t1: TERMINATED Thread t2: TERMINATEDCopy the code
T1 uses tryLock() to obtain the lock, which is now owned by T0. So return false and the code continues. While T2 waits for the lock normally and continues to complete the execution after obtaining the lock.