代码之家  ›  专栏  ›  技术社区  ›  vitaminC

执行程序时无法理解tryLock方法

  •  0
  • vitaminC  · 技术社区  · 2 年前

    我正在学习Java并发性,并尝试ReentrantLock类方法。当尝试tryLock()方法并运行示例程序时,它并没有正常工作。根据定义,如果锁可用,则tryLock()返回true,线程将获得锁&如果不是,则返回false。

    所以在我的代码中,我有两个线程,如果t1锁定,那么它将执行if部分操作,t2将执行else操作。我是不是错过了什么?请帮忙。

    代码:

    import java.util.concurrent.locks.ReentrantLock;
    
    class ReentrantLockMethods extends Thread{ 
        ReentrantLock l = new ReentrantLock();  
        
        public ReentrantLockMethods(String name) {
            super(name);
        }   
    
        public void run() {     
            if(l.tryLock()) {           
                System.out.println(Thread.currentThread().getName()+"....got Lock and performing safe operations");
                try {
                    Thread.sleep(5000);
                }
                catch(InterruptedException e) {}
                l.unlock();         
            }
            else {
                System.out.println(Thread.currentThread().getName()+ "....unable to get Lock hence, performing alternate operations");
            }
        }
    }
    
    public class ReentrantLockDemo1 {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            ReentrantLockMethods t1 =  new ReentrantLockMethods("First Thread");
            ReentrantLockMethods t2 =  new ReentrantLockMethods("Second Thread");       
            t1.start();
            t2.start();
        }
    
    }
    

    实际输出:

    First Thread....got Lock and performing safe operations
    Second Thread....got Lock and performing safe operations
    

    预期输出:

    First Thread....got Lock and performing safe operations
    Second Thread....unable to get Lock hence, performing alternate operations
    

    Second Thread....got Lock and performing safe operations
    First Thread....unable to get Lock hence, performing alternate operations
    
    1 回复  |  直到 2 年前
        1
  •  0
  •   Mark Rotteveel    2 年前

    在您的实施中 ReentrantLockMethods ,每个实例都有自己的锁,因此不存在争用,并且两者都可以获取自己的锁。如果要观察所需的行为,则需要确保两个线程使用相同的锁。

    顺便说一句,通常你不应该延长 Thread ,而是实现 Runnable