Java | Terminating all child threads if parent thread is terminated - java

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());
}
}

Java automatically groups Threads. If you do not define a specific ThreadGroup,
it will always grouped as child of the thread where the initialization takes place.
So if you abort a parent Thread, all its childThreads will be aborted too.
perhaps this could help (sorry that it's in german): dpunkt programming pdf

Related

Java Thread.sleep not working as expect in runnable implement

I am trying to figure out how Thread.sleep works, so I create the following piece of code:
public static void main() {
Runnable runnable = new Runnable() {
public void run() {
try {
Thread.sleep(1000);
System.out.println("Middle");
} catch (InterruptedException e) {
}
}
};
System.out.println("Before");
Thread t2 = new Thread(runnable);
t2.start();
System.out.println("After");
However, it only prints Before and After in the console and skips the Middle.
So I am wondering whether this Thread.sleep will break the Runnable part??
On my machine output of your code is:
Before
After
Middle
If you want to print Middle before After you need to add t2.join() method call right after t2.start(). Join method explanation.
Use join () to make your main thread wait till your thread (t2) execution finishes.
public static void main(String[] args) throws InterruptedException {
Runnable runnable = new Runnable() {
public void run() {
try {
Thread.sleep(1000);
System.out.println("Middle");
} catch (InterruptedException e) {
}
}
};
System.out.println("Before");
Thread t2 = new Thread(runnable);
t2.start();
t2.join();
System.out.println("After");
Output:
Before
Middle
After
Refer to this post to know about join() : What does this thread join code mean?
Refer to this post to know about the main thread: When does the main thread stop in Java?

Cyclic barrier await method not working

I am trying to learn multithreading and was trying with a cyclic barrier. I understand that to break the barrier an await method must be called by the number of the thread mentioned while creating the barrier. I am trying to do the same but when I check if the barrier is broke my main method is going in an infinite loop.
class CyclicBarrierTrial implements Runnable{
CyclicBarrier barrier;
public CyclicBarrierTrial(CyclicBarrier barrier){
this.barrier=barrier;
}
public void run() {
System.out.println("in the run method");
try {
Thread.sleep(1000);
System.out.println("going to call awake on barrier"+ Thread.currentThread().getName());
try {
barrier.await();
} catch (BrokenBarrierException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("barrier broke");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println("Wake up from the Sleep"+ Thread.currentThread().getName());
}
}
public class MYCountDownLatch {
public static void main(String[] args) throws InterruptedException {
CyclicBarrier barrier = new CyclicBarrier(2);
Thread t1= new Thread(new CyclicBarrierTrial((barrier)));
t1.start();
Thread t2= new Thread(new CyclicBarrierTrial((barrier)));
Thread.sleep(2000);
t2.start();
while(!barrier.isBroken())
{
System.out.println("waiting for the barrier to break "+barrier.isBroken());
}
System.out.println("MAIN THREAD finally barrier to broke ");
}
}
barrier.isBroken() indicates if barrier is in broken state, which is different than barrier is tripper.
To check this, you can try interrupting one of thread, this will raise BarrierBrokenException on other threads and barrier.isBroken() will be true.
Thread.currentThread().interrupt();
If you want to wait for all threads to complete, then you can use ExecutorService.awaitTermination or Thread.join
From documentation:
If any thread is interrupted while waiting, then all other waiting threads will throw BrokenBarrierException and the barrier is placed in the broken state.
Hope this help.

why i am getting error while implementingInterThread Communication in java using wait and notify?

I am implementing a simple example of SimpleInterThreadCommunication and have used wait and notify.
I am getting an error on total in InterThread class can anyone explain why
public class InterThread
{
public static void main(String s[])throws InterruptedException
{
Thread b=new Thread();
b.start();
Thread.sleep(10);
synchronized (b)
{
System.out.println("Main thread trying to call wait");
b.wait();
System.out.println("Main thread got notifies");
System.out.println(b.total); //error here total cannot be resolved to a field
}
}
}
class ThreadB extends InterThread
{
int total=0;
public void run()
{
synchronized(this)
{
System.out.println("child thread got notifies");
for(int i=0;i<3;i++)
{
total=total+i;
}
System.out.println("child thread ready to give notification");
this.notify();
}
}
}
You need to create Object of ThreadB class then you can access total field.
it is not visible to Thread class object.
You have created b object Of Thread class and in Thread class no any such field named as total available.
change your code something like below:
ThreadB b1=new ThreadB();
System.out.println(b1.total);
Answer i made changes after suggestion from helpful people
Here is the corrected code
public class InterThread
{
public static void main(String s[])throws InterruptedException
{
ThreadB b=new ThreadB(); //correction 1
b.start();
Thread.sleep(10);
synchronized (b)
{
System.out.println("Main thread trying to call wait");
b.notify(); //correction2
System.out.println("Main thread got notifies");
System.out.println(b.total);
}
}
}
class ThreadB extends InterThread
{
int total=0;
public void run()
{
synchronized(this)
{
System.out.println("child thread got notifies");
for(int i=0;i<3;i++)
{
total=total+i;
}
System.out.println("child thread ready to give notification");
try
{
System.out.println("child thread ready trying to call wait");
this.wait(); //corrected 3
}
catch(InterruptedException e)
{
System.out.println("interrupted Exception");
}
}
}
}

How the join() method in Java works?

class JoinDemo extends Thread {
JoinDemo(String nm) {
setName(nm);
start();
}
public void run() {
for (int i = 1; i <= 5; i++) {
try {
Thread.sleep(100);
} catch (Exception e) {
System.out.println(e);
}
System.out.println(i);
}
System.out.println(getName() + " exiting.");
}
public static void main(String args[]) {
JoinDemo t1 = new JoinDemo("One");
JoinDemo t2 = new JoinDemo("Two");
JoinDemo t3 = new JoinDemo("Three");
try {
t1.join();
} catch (Exception e) {
System.out.println(e);
}
System.out.println("Main Thread Exits now.");
}
}
The output obtained is:
1
1
1
2
2
2
3
3
3
4
4
4
5
5
Three exiting.
One exiting.
5
Main Thread Exiting
Two exiting.
I wrote the above program after going through various sites to understand the concept of Join(). But still i'm unable to get it.The problem I'm facing is that I have used t1.join(). So thread one should exit before three, but here thread three exits before one. And every time I run the program the output is different. As sometimes it is two exiting before one, or three before one. Shouldn't thread one exit before any other thread?? As t1.join() waits for thread one to terminate before three and one??
No you mistook the effect of join().
when you do a t1.join()you are just asserting that the thread t1 will be finished before continuing the program.
As you can see it's what you have,
One exiting.
5
Main Thread Exiting
One exit before the end of the main symbolized by the Main Thread Exiting.
If you want your program to finish all the thread before finishing you should do :
try {
t1.join();
t2.join();
t3.join();
} catch (Exception e) {
System.out.println(e);
}
If you want One to finish then 2 then 3
JoinDemo t1 = new JoinDemo("One");
try {
t1.join();
} catch (Exception e) { System.out.println(e); }
JoinDemo t2 = new JoinDemo("Two");
try {
t2.join();
} catch (Exception e) { System.out.println(e); }
JoinDemo t3 = new JoinDemo("Three");
try {
t3.join();
} catch (Exception e) { System.out.println(e); }
To know exactly what join() is doing,
JoinDemo t1=new JoinDemo("One");
t1.join();
JoinDemo t2=new JoinDemo("Two");
JoinDemo t3=new JoinDemo("Three");
Just call the method after declaring t1 and see.
join() method will make the already initialized Thread to complete first.So other Threads will wait till then.
t1.join() simply ensures that your main thread will block until t1 has completed. You have no control over how quickly t1 will finish compared to the other two threads.
t1, t2 and t3 are at the mercy of the thread scheduler. The only guarantee you have in your code is that t1 will finish before the main thread.
You are running 3 different threads. The priority or amount of CPU used for each thread depends on the java implementation, in some cases it's done by the OS. That's why you get a different output.
Joins makes the running thread wait until the joint thread dies.
I think you want this output:
class JoinDemo extends Thread {
JoinDemo(String nm) {
setName(nm);
}
public void run() {
for (int i = 1; i <= 5; i++) {
try {
Thread.sleep(100);
} catch (Exception e) {
System.out.println(e);
}
System.out.println(i);
}
System.out.println(getName() + " exiting.");
}
public static void main(String args[]) {
JoinDemo t1 = new JoinDemo("One");
JoinDemo t2 = new JoinDemo("Two");
JoinDemo t3 = new JoinDemo("Three");
try {
t1.start();
t1.join();
t2.start();
t2.join();
t3.start();
t3.join();
} catch (Exception e) {
System.out.println(e);
}
System.out.println("Main Thread Exits now.");
}
}

Need sample program to throw InterruptedException

I am going through the kathy sierra SCJP 1.5 Chapter 9(threads) and there it is mentioned as:
Notice that the sleep() method can throw a checked InterruptedException
(you'll usually know if that is a possibility, since another thread has to explicitly do
the interrupting), so you must acknowledge the exception with a handle or declare
I just need a sample program to know when it happens (which i can run on my machine)?
I googled but could not find any sample code to test this functionality..
Thanks in Advance
Here's an example:
public class Test
{
public static void main (String[] args)
{
final Thread mainThread = Thread.currentThread();
Thread interruptingThread = new Thread(new Runnable() {
#Override public void run() {
// Let the main thread start to sleep
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
mainThread.interrupt();
}
});
interruptingThread.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("I was interrupted!");
}
}
}
To walk through it:
Set up a new thread which will sleep for a short time, then interrupt the main thread
Start that new thread
Sleep for a long-ish time (in the main thread)
Print out a diagnostic method when we're interrupted (again, in the main thread)
The sleep in the main thread isn't strictly necessary, but it means that the main thread does get to really start sleeping before it's interrupted.
public class SleepTest1 extends Thread {
#Override
public void run() {
try {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName());
Thread.sleep(1000);
Thread.currentThread().interrupt();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SleepTest1 st1 = new SleepTest1();
st1.start();
}
}

Categories

Resources