Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k 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 Reply

0 votes
by (71.8m points)

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

Lock lock = new ReentrantLock();

这个不是吗?

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...