I am trying to write a thread that keeps track of how long a blocking action takes. For example, I have a blocking action like this:
class BlockingThread extends Thread{ public volatile boolean success = false; public volatile long startedTime = 0; public void run(){ startedTime = System.currentTimeMillis(); success = doBlockingAction();
and I want to have another Thread that basically calls the "timeout" function if the lock action takes too long:
class MonitorThread extends Thread{ public void run(){ while(System.currentTimeMillis() - blockingThread.startedTime > TIMEOUT_DURATION) { ..keep waiting until the time runs out.. } if(!blockingThread.success){ listener.timeout();
I'm having trouble understanding how BlockingThread is actually currently in a blocking action while I measure time in MonitorThread.
If I do something like this,
Thread blockingThread = new BlockingThread(); blockingThread.start(); Thread monitorThread = new MonitorThread(); monitorThread.start();
there is no guarantee that one of the threads actually runs the code in front of the other, and therefore I do not currently know if my time stream really measures the time of the blocking action. I assume the answer is related to locking and wait ing, but I cannot figure it out.
source share