Controlling a thread's processing time

Hey there. I know this subject is found everywhere, but I really couldn't find an answer to my problem... yet :)

I have to support Runnable object not written by me, so I don't have access to their source code (decompiling them is not an option). So, I can't rewrite the run() method. Example:

publicclass MyClassextends Runnable{

...

publicvoid run(){

sleep(10000);//sleep for 10 seconds

}

...

}

I need to do something like

new Thread(new MyClass()).start();

make it run and, if it takes longer than x seconds, then stop them no matter what, even if they leave some corrupt variables.

I tried plenty of things but couldn't make it work. Pseudo code could be somthing like:

Thread t =new Thread(new Myclass());

t.start();

Waitfor t to terminatefor 3 seconds;//note that I can't use t.wait(3000), since I can't call notify() from inside t.

If (t didn't finalize yet)

Kill the bastard and System.out.println("Forced to terminate!");

else

System.out.println("Great job!");

Also, if the thread ends before the 3 seconds period, I would like not to keep waiting for the 3 seconds. That is, I don't want to call Thread.sleep(3000) after t.start();

Any piece of advise here? Thanks in advance!

[1983 byte] By [SebasGRa] at [2007-10-2 18:30:35]
# 1
t.wait(3000);is a strong contender. Could you please explain why you can not do it?
BIJ001a at 2007-7-13 19:51:59 > top of Java-index,Other Topics,Algorithms...
# 2

Hello,

You better use the join(ms) method.

Join(ms) will finish on the following condition :

you wait till ms

the thread is finish

ex :

Thread l_t = new MyThread();

l_t.start();

try{

l_t.join(3000): // current thread will wait max 3s

} catch( InterruptException l_e ){

}

if( l_t.isAlive() ) kill the buster !!!

hope this help... but i guess you already found the solution ;-))

wavesridera at 2007-7-13 19:51:59 > top of Java-index,Other Topics,Algorithms...
# 3

Extending further on the defined problem if say there are multiple threads invoked

Thread threads[] = new Thread[10]

for (int = 0 , i < 10 ; i++) {

threads= new Thread();

threads.start();

}

If the main thread should wait for max X seconds would it be possible to use join(ms) or I have to do an explicit wait and then kill all alive threads in the array?

Would there be any concurrency issues related to the approach?

borntougha at 2007-7-13 19:51:59 > top of Java-index,Other Topics,Algorithms...