简体   繁体   中英

How does a lock work in Java?

Suppose I have 2 instances of a CustomThread and one common object instance called printer . Inside the print method of printer , if I do a lock.lock() and lock.unlock() at the end, how does this work?

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? 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 .

When lock() is called, and owner is null , owner is assigned to the calling thread. When unlock() is called, owner is reset to 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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