Hi,
I have main thread which calls another thread. timeout period of second one is 15 seconds. Current implementaion is main thread check second one for every 2 seconds. What I need to do is wait for only as long as second thread finish, upto a maximum of 15 seconds. I thought of trying wait and notify, but it will require synchronized. I am thinking of using Lock. I havent tried it before. Please help me on this.
Thanks
This idea can be implemented? by using timedwait on a lock object in the first thread. The second thread once done should notify on the lock object. This will wake up the first thread. Also, timedwait will force a max wait of 15 seconds.
Updated the solution, I tried.
public class MyThread {
Object obj = new Object();
boolean isDone = false;
int timeOut = 0;
int runTime = 0;
int id = 0;
public static void main(String[] args) throws Exception {
MyThread mainThread = new MyThread();
mainThread.timeOut = Integer.valueOf(args[0]);
mainThread.runTime = Integer.valueOf(args[1]);
System.out.println("<---- mainThread.timeOut ---------->" + mainThread.timeOut);
System.out.println("<---- mainThread.runTime ---------->" + mainThread.runTime);
ChildThread childThread = new ChildThread(mainThread);
childThread.start();
try {
synchronized (mainThread.obj) {
//Wait the current Thread for 15 seconds
mainThread.obj.wait(mainThread.timeOut * 1000);
}
System.out.println("<---- runTime Over ---------->");
if (mainThread.isDone)
System.out.println("<---- done ---------->");
else
System.out.println("<---- not done ---------->");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void test() {
System.out.println("<--- In business Test method --->");
try {
//Call the bussiness method which may take more time
Thread.sleep(runTime * 1000);
if (runTime <= timeOut)
isDone = true;
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("<---- completes business test method -->");
}
}
class ChildThread extends Thread {
MyThread mainThread;
ChildThread(MyThread mainThread) {
this.mainThread = mainThread;
}
public void run() {
System.out.println("ChildThread: the run method");
mainThread.test();
//Finished the work,notify the waiting thread.
synchronized(mainThread.obj) {
mainThread.obj.notify();
}
}
}