简体   繁体   English

在Java中检查对对象的锁定

[英]Check the Lock on an object in java

I want to check the lock on an object of the class. 我想检查该类对象上的锁。 I use Thread.holdsLock(this) for this. Thread.holdsLock(this)使用Thread.holdsLock(this) Is this the Right way? 这是正确的方法吗?

My question is how I can check if the object is locked for the main method and also check the lock on static methods. 我的问题是我如何才能检查对象是否为main方法锁定,以及如何检查静态方法的锁定。

public class CheckLock {
    public static void main(String[] args) throws InterruptedException {
        objectLockClass olc=    new objectLockClass();
        Thread t1=new Thread(olc);
        t1.start();
    }
}

class objectLockClass implements Runnable {

    @Override
    public void run() {
        boolean isLocked = true;
        int counter=0;     
        synchronized (this) {
            while (isLocked) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("lock object in run  : " + Thread.holdsLock(this));
                if (counter==5 ) isLocked=false;
                    counter++;
            }
        }

The output is: 输出为:

lock object in run  : true
lock object in run  : true
lock object in run  : true
lock object in run  : true
lock object in run  : true
lock object in run  : true

how I can check the object is locked for main method and also check lock on static methods? 如何检查对象的main方法是否已锁定,以及如何检查静态方法的锁定?

An object isn't locked for a method . 没有为方法锁定对象。 It's just locked. 它只是被锁住了。 period. 期。 The utility of Java's synchronized keyword is that no two threads will ever be allowed to synchronize on the same object at the same time. Java的synchronized关键字的实用程序是,永远不允许两个线程同时在同一个对象上进行同步。


It doesn't usually make sense to ask whether some other thread has an object locked. 询问其他线程是否已锁定对象通常没有任何意义。 The Thread.holdsLock(foo) method won't tell you that: It only tells whether the calling thread has foo locked. Thread.holdsLock(foo)方法不会告诉您:它仅告诉调用线程是否已将foo锁定。 Suppose there was a method, Thread.otherThreadHoldsLock(foo) , and suppose you called it like this: 假设一个方法, Thread.otherThreadHoldsLock(foo) ,并假设你称它是这样的:

Object foo = ...;

if (Thread.otherThreadHasLocked(foo)) {
    doSomething();
} else {
    doSomethingElse();
}

It doesn't give you any useful information: This code could call doSomething() with foo locked, or with foo not locked; 它没有提供任何有用的信息:此代码可以在foo锁定或foo不锁定的情况下调用doSomething(); and it could call doSomethingElse() with foo locked, or with foo not locked. 并且可以在foo锁定或foo未锁定的情况下调用doSomethingElse()。 There's no guarantee, because another thread could acquire the lock or release the lock at any time. 不能保证,因为另一个线程可以随时获取锁或释放锁。

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

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