【问题标题】:Is there a way to count accesing threads to a primitive variable?有没有办法计算访问线程到原始变量的数量?
【发布时间】:2019-10-25 14:24:11
【问题描述】:

我的代码中有一个变量,一个简单的原始布尔值 x。由于代码复杂性,我不确定访问它的线程数。也许它从不共享,或者只被一个线程使用,也许不是。如果它在线程之间共享,我需要使用AtomicBoolean

有没有办法计算访问布尔 x 的线程数?

到目前为止,我对代码进行了审查,但它非常复杂并且不是我编写的。

【问题讨论】:

  • 是直接访问属性,还是私有,通过getter访问?
  • 到目前为止,您尝试过什么样的评论?您应该能够跟踪实现Runnable 或从Thread 继承的所有类,如果其中任何一个访问该变量,它可能会被共享。
  • 另外,这可能会有所帮助:dzone.com/articles/…
  • @bracco23 有一些 PropertyChangeListener 可以访问它。没有一个类实现 Runnable 或扩展 Thread 类。
  • @Bentaye 是私有的,由 setter 访问

标签: java multithreading atomicboolean


【解决方案1】:

每当新线程尝试获取原始值时,始终使用 getter 访问变量并写下获取线程 id 的逻辑。每当线程终止时,使用关闭挂钩从该列表中删除该 threadId。该列表将包含当前持有对该变量的引用的所有线程的 ID。

 getVar(){
countLogic();
return var;}

countLogic(){
if(!list.contains(Thread.getCurrentThread().getId)){
list.add(Thread.getCurrentThread().getId);
Runtime.getRuntime().addShutdownHook(//logic to remove thread id from the list);
}

希望对你有帮助

【讨论】:

    【解决方案2】:

    如果这只是为了测试/调试目的,你可以这样做:

    如果还没有,请通过 getter 公开布尔值并计算 getter 中的线程数。这是一个简单的例子,我列出了所有访问 getter 的线程:

    class MyClass {
    
        private boolean myAttribute = false;
    
        private Set<String> threads = new HashSet<>();
        public Set<String> getThreadsSet() {
            return threads;
        }
    
        public boolean isMyAttribute() {
            synchronized (threads) {
                threads.add(Thread.currentThread().getName());
            }
            return myAttribute;
        }
    
    }
    

    然后就可以测试了

    MyClass c = new MyClass();
    
    Runnable runnable = c::isMyAttribute;
    
    Thread thread1 = new Thread(runnable, "t1");
    Thread thread2 = new Thread(runnable, "t2");
    Thread thread3 = new Thread(runnable, "t3");
    
    thread1.start();
    thread2.start();
    thread3.start();
    
    thread1.join();
    thread2.join();
    thread3.join();
    
    System.out.println(c.getThreadsSet());
    

    这个输出:

    [t1, t2, t3]
    

    编辑: 刚刚看到您添加了通过setter访问属性,您可以调整解决方案并在setter中记录线程

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-27
      • 2020-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 2020-12-23
      • 2023-02-21
      相关资源
      最近更新 更多