multithreading - Killing Process after specific time(Java) -
i want have mechanism expected process shouldn't run more specific time. after specific time over, status whether process running or not should displayed , process should no longer run.
for tried make 2 classes execute
, check
, execute
object's run method execute process. check
object sleep specific time, after checks whether object of execute
still running. if running check
object expected kill thread , print "yes". else, check
object should print "no".
class execute extends thread{ public void run(){ //execute process } public static void main(string[] args){ execute ex = new execute(); ex.start(); check ch = new check(ex); ch.start(); } } class check extends thread{ execute ex; check(execute ex){ this.ex = ex; } public void run(){ try{thread.sleep(5000);} //specific time given 5 seconds. catch(exception e){system.out.println(e);} if(ex.isalive()){ system.out.println("yes"); //kill thread ex. } else system.out.println("no"); } }
my questions are:
- how can kill
ex
thread? - what best way implement mechanism?
there no 100% safe way in java.
the recommend approach interrupt execute thread
if(ex.isalive()){ system.out.println("yes"); //kill thread ex. ex.interrupt() }
but work, inside execute run() method logic need check if interrupted()
returns true , if so, stop computations (for example if run method in loop, first statements inside loop check. interrupt break "blocking" operations wait(), sleep(), io operations, affect both "code" , let's call them "system" methods (that why example sleep throws interruptedexception
).
nevertheless need in control of run() method code add necessary checks , stops execution.
the hardcore way of stoping thread calling
ex.stop()
as can see in javadoc deprecated , should not used can cause problems (read doc). way of stoping thread exectues code don't have control over.
my approach be, first interrupt, wait see if worked , if not forcible stop thread.
if(ex.isalive()){ system.out.println("yes"); //kill thread ex. ex.interrupt(); ex.join(100); //give ex thread chance stop in clean way if (ex.isalive()) { ex.stop(); } }
Comments
Post a Comment