简体   繁体   English

如何检查线程是否在同步块或方法中?

[英]How can I check if a thread is inside a synchronized block or method?

My Java application uses two Threads. 我的Java应用程序使用两个Threads。 Historically grown, there are synchronized methods and dedicated lock objects in use. 从历史上看,有使用的同步方法和专用锁定对象。 I need to know wether the current thread has a lock and if it is by method or object. 我需要知道当前线程是否有锁,如果是方法或对象。 How can I do this? 我怎样才能做到这一点?

When entering a synchronized method the VM sets a lock on the current object. 当输入同步方法时,VM会在当前对象上设置锁定。 Thus the following codes have the same effect: 因此,以下代码具有相同的效果:

synchronized void syncMethod() {
    // do something
}

void syncManually() {
    synchronized (this) {
        // do something
    }
}

That means the synchronized method does exactly the same as 这意味着synchronized方法与完全相同

synchronized( lock ) {
    // do something
}

anywhere in your code. 代码中的任何位置。

You can use Thread.holdsLock(...) to check if the thread holds a specific lock. 您可以使用Thread.holdsLock(...)来检查线程是否包含特定锁。 Here is an example code: 这是一个示例代码:

final Object lock = new Object(); 

public void lockDemo() {

    System.out.println( Thread.holdsLock(lock) );     // false
    System.out.println( Thread.holdsLock(this) );     // false

    synchronized ( lock ) { 
      System.out.println( Thread.holdsLock(lock) );   // true: locked by object
      System.out.println( Thread.holdsLock(this) );   // false
    }

    doSyncMethod();
}

public synchronized void doSyncMethod() {
    System.out.println( Thread.holdsLock(lock) );  // false
    System.out.println( Thread.holdsLock(this) );  // true: locked by synchronized method
}

Since Java 1.5 more sophisticated locks like ReentrantReadWriteLock are supported by the java.util.concurrent.locks package. 自Java 1.5以来, java.util.concurrent.locks包支持更复杂的锁,如ReentrantReadWriteLock They can provide separated read and write locking and improve the performance of your application. 它们可以提供独立的读写锁定并提高应用程序的性能。 The Lock Objects chapter of the Oracle Java Tutorials is a good start here. Oracle Java Tutorials的Lock Objects一章是一个很好的开始。

If you manually request a thread-dump the JVM will print out a stack-trace of each thread including what objects/methods are locked or waiting on a synchronized block. 如果手动请求线程转储,JVM将打印出每个线程的堆栈跟踪,包括锁定或等待同步块的对象/方法。

You can manually request a thread-dump by sending the JVM process a SIGQUIT in *nix or by typing CTRL-Break (not Ctrl-C ) in a Windows command-prompt window where the JVM was started. 您可以通过在* nix中向JVM进程发送SIGQUIT或在启动JVM的Windows命令提示符窗口中键入CTRL-Break (而不是Ctrl-C )来手动请求线程转储。

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

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