I want to have mechanism by which expected process shouldn't run more than specific time. After specific time is over, status whether process is running or not should be displayed and process should no longer run.
For that I tried to make two classes Execute
and Check
, Execute
object's run method will execute process. Check
object will sleep for specific time, after which it checks whether object of Execute
is still running. If it is running Check
object is expected to kill that thread and 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 is 5 seconds.
catch(Exception e){System.out.println(e);}
if(ex.isAlive()){
System.out.println("yes");
//kill the thread ex.
}
else System.out.println("no");
}
}
My questions are:
- How can I kill
ex
thread? - What is the best way to implement this mechanism?