我的代码中有一个变量,一个简单的原始布尔值 x。由于代码复杂性,我不确定访问它的线程数。也许它从不共享,或者只被一个线程使用,也许不是。如果它在线程之间共享,我需要使用它AtomicBoolean
来代替。
有没有办法计算访问布尔 x 的线程?
到目前为止,我对代码进行了审查,但它非常复杂并且不是我编写的。
我的代码中有一个变量,一个简单的原始布尔值 x。由于代码复杂性,我不确定访问它的线程数。也许它从不共享,或者只被一个线程使用,也许不是。如果它在线程之间共享,我需要使用它AtomicBoolean
来代替。
有没有办法计算访问布尔 x 的线程?
到目前为止,我对代码进行了审查,但它非常复杂并且不是我编写的。
如果这只是为了测试/调试目的,你可以这样做:
如果还不是这种情况,请通过 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 中记录线程
每当新线程尝试获取原始值时,始终使用 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);
}
希望能帮助到你