有没有办法检查有多少线程正在等待同步方法解锁?
解:
我用堆垛机解决了这个问题:
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)); } }
解决方法
您可以将代码转换为使用同步块而不是同步方法,这是我的粗略草案.我不知道它是否符合你的第二个要求(由于我的破碎英语)
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)); } } }