Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
770 views
in Technique[技术] by (71.8m points)

Java:请教这段代码中 lock 的究竟是哪个对象

public class Solution {
    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Thread t1 = new Thread(()->{
            try {
                lock.lock();
                System.out.println("线程一启动");
                TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
                System.out.println("线程一结束");
            } catch (InterruptedException e) {
                System.out.println("线程一中断");
            } finally {
                lock.unlock();
            }
        }); 
        Thread t2 = new Thread(()->{
            try {
                lock.lock();
                System.out.println("线程二启动");
                TimeUnit.SECONDS.sleep(5);
                System.out.println("线程二启动");
            } catch (InterruptedException e) {
                System.out.println("线程二中断");
            } finally {
                lock.unlock();
            }
        }); 
        t1.start();
        t2.start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.interrupt();
    }
}

程序输出结果仅有【线程一启动】,线程二不会被执行
请教在线程 t1 中的 lock.lock() 究竟是锁的哪个对象?没看到程序里有显式声明对象


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

请教在线程 t1 中的 lock.lock() 究竟是锁的哪个对象?

Lock lock = new ReentrantLock();

这个不是吗?

lambda表达式可以访问调用者的局部变量。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...