有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如果已经调用了另一个线程,java不会调用静态方法

我有一个静态方法,如果另一个线程调用它,我想立即返回它
例如

public static void parseNetworkData() {  
   if(isRunning) {  
     return;
   }  
   // get and cache network data  
   // for use  
}  

我真的不想同步这个方法,因为如果网络调用已经完成,我不希望其他线程也这样做
现在我不确定以下几点:
考虑到这是一个静态方法,定义/处理isRunning的最佳方式是什么
我应该将其转换为实例方法吗


共 (2) 个答案

  1. # 1 楼答案

    使旗帜不稳定且静止

    volatile static boolean isRunning
    
  2. # 2 楼答案

    I have a static method that I am interested in returning immediately if another thread has called it.

    这听起来很可疑,但你可以做到。方法是static对这种情况没有太大影响,但是无论怎样,都需要应用同步或并发支持对象来管理线程之间的交互。在这种情况下,java.util.concurrent.ReentrantLock可以方便地提供您需要的:

    class MyClass {
        private static ReentrantLock networkDataLock = new ReentrantLock();
    
        public static void parseNetworkData() {  
            if (!networkDataLock.tryLock()) {
                // a different thread has the lock
                return;
            }
            try {
                // get and cache network data  
                // for use  
            } finally {
                // If the lock was successfully acquired then it must be
                // unlocked without fail before the method exits
                networkDataLock.unlock();
            }
        }  
    }