简体   繁体   English

Java中的锁如何工作?

[英]How does a lock work in Java?

Suppose I have 2 instances of a CustomThread and one common object instance called printer . 假设我有2个CustomThread实例和一个称为printer公共对象实例。 Inside the print method of printer , if I do a lock.lock() and lock.unlock() at the end, how does this work? printerprint方法内部,如果我在最后执行lock.lock()lock.unlock() ,这如何工作?

private class Printer{

        private final Lock mutex = new ReentrantLock(true);

        public void print(int thread){
            try {
                mutex.lock();
                for(int i = 0; i < 10; ++i) {
                    System.out.println(String.format("Printing: %d for Thread: %d", i, thread));
                }
            } catch(Exception e){

            } finally {
                mutex.unlock();
            }
        }
    }

I will call this method from 2 of my thread objects. 我将从我的两个线程对象中调用此方法。

My question is, how does the method lock itself? 我的问题是,该方法如何lock自身? Isn't a lock based on a thread? 锁不是基于线程的吗? Maybe I am confusing the core idea here. 也许我在这里混淆了核心思想。 When I do a lock inside a method, what does it mean? 当我在方法内部进行锁定时,这意味着什么?

You can think of it as if a lock has a field called owner , which is a Thread . 您可以认为锁好像有一个名为owner的字段,该字段是Thread

When lock() is called, and owner is null , owner is assigned to the calling thread. lock()调用且ownernullowner被分配给调用线程。 When unlock() is called, owner is reset to null . 调用unlock()owner重置为null

When lock() is called, and owner is not null (and not the current thread, since the lock is re-entrant), the calling thread blocks until another thread relinquishes ownership and it can be assigned as the new owner. 当调用lock()owner不为null (并且不是当前线程,因为该锁是可重入的)时,调用线程将阻塞,直到另一个线程放弃所有权为止,并且可以将其分配为新所有者。

The additional complication is that the check for the current ownership, and the conditional assignment of the current thread as the new owner, both have to be seen to occur atomically by other threads. 额外的麻烦在于,必须检查当前线程是否拥有所有权,以及将当前线程作为新所有者的条件分配,都必须由其他线程自动进行。 This preserves the integrity of the lock. 这保留了锁的完整性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM