Tob*_*s M 11 java multithreading synchronization
有没有办法检查有多少线程在等待同步方法解锁?
我想知道线程何时调用synchronized方法:
1)已经有多少线程在等待调用该方法?
2)一旦调用该方法需要等待该方法解锁多长时间?
解决方案:我使用堆垛机解决了这个问题:
public class LockedClass {
public static int count;
public static void measuringClass() throws IOException{
long startTime = System.currentTimeMillis();
count++;
System.out.println("Threads waiting="+count);
lockedMethod(startTime);
count--;
System.out.println("Threads waiting="+count);
}
public static synchronized void lockedMethod(long startTime) throws IOException{
System.out.println("I spent="+(System.currentTimeMillis()-startTime)+" in the queue");
Hashtable<String, String> params = new Hashtable<String, String>();
params.put("param1", "test");
params.put("param2", "12345678");
String sessionId = Common.getSession(Common.executeHttpRequest(params));
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将代码转换为使用同步块而不是同步方法,这是我的草稿。我不确定它是否符合您的第二个要求(由于我的英语不稳定)
public class Sync {
public static int waiting = 0;
private Object mutex = new Object();
public void sync() {
waiting++;
synchronized (mutex) {
waiting--;
long start = System.currentTimeMillis();
doWhatever();
System.out.println("duration:"
+ (System.currentTimeMillis() - start));
}
}
}
Run Code Online (Sandbox Code Playgroud)