Please help me with this Main thread/ Parent thread will triggers sub threads. If we are stopping parent/main thread it must also stop all child/sub threads
I am thinking to do it with interrupts but not able to do it Please help me out with the code
and how to ensure all child threads have been stopped?IS there any way to do this also
Thanks in Advance!
I am trying to do something like this :
public class ThreadTest1 extends Thread{ private static final Logger LOGGER = Logger.getLogger("mylogger");
public void run(){
for(int i=1;i<=5;i++){
try{
if (!Thread.currentThread().isInterrupted()) {
LOGGER.log(Level.SEVERE,"Sleeping...");
Thread.sleep(1000);
LOGGER.log(Level.SEVERE,"Processing");
System.out.println(Thread.currentThread().getId()+"Thread id: "+i);
}
else{
throw new InterruptedException();
}
}catch(InterruptedException e){
System.out.println(e);
LOGGER.log(Level.SEVERE,"Exception", e);
Thread.currentThread().interrupt();
}
}
}
public static void main(String args[]){
ThreadTest1 t1=new ThreadTest1();
ThreadTest1 t2=new ThreadTest1();
ThreadTest1 t3=new ThreadTest1();
System.out.println(t1.getId());
System.out.println(t2.getId());
System.out.println(t3.getId());
t1.start();
t2.start();
t3.start();
System.out.println("Do you want to kill all processes: Press any key to continue");
int s=0;
try {
s = System.in.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(s!=0){
t1.interrupt();
t2.interrupt();
t3.interrupt();
}
System.out.println(t1.isAlive());
}
}
Please help me out with the code
Which code? You should put your code here to let others know what you are trying to do. – gprathourThreadGroup
will help? If you put all child threads in the sameThreadGroup
, you can interrupt them all. The child threads still have to cooperate by checking periodically. – ajbt1.isAlive
. The interrupt will take a little time to process. Also, are you sure it recognized the input? On many systems, if you simply "press a key", the input will not get to the program until you press ENTER or RETURN. – ajb