user3239652
user3239652

Reputation: 785

How to stop one thread after completion of other?

class test
{
    public static void main(String[] args) {


        Thread th=new Thread()
        {

            public void run(){

                for (int i = 1; i <= 18; i++) {
                    System.out.println("run:"+i);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                    }
                }   

            }};
            Thread y=new Thread()
            {
                public void run() {
                    for (int i = 1; i < 10; i++) {
                        System.out.println("stop:"+i);
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                        }
                    }   

                }

            };

            th.start();
            y.start();
            for (int i = 0; i < 5; i++) {
                System.out.println("main:"+i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block

                }

            }
            System.out.println("main completed");
    }   

}

Here i want to stop Thread th as soon as thread y completes its execution,how can I do that?

Upvotes: 2

Views: 186

Answers (7)

Bob Cross
Bob Cross

Reputation: 22292

Here i want to stop Thread th as soon as thread y completes its execution,how can I do that?

Java has provided you exactly the method you need. All you need to do is fill in your "TODO" blocks.

Quoting from the JDK documentation for the interrupt method:

Interrupts this thread.

... [snip]

If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

So, thread y can call the interrupt method on the thread th and cause it to receive an InterruptedException. That's exactly why those checks are there for the sleep() calls. Now, just fill them in and you'll have exactly what you need:

class test
{
    public static void main(String[] args) {
        Thread th=new Thread()
        {
            public void run(){
                for (int i = 1; i <= 18; i++) {
                    System.out.println("run:"+i);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {

                        // Here is one way that you can immediately exit th
                        System.out.println("Thread th was interrupted.");
                        System.out.println("y must have finished");
                        break;
                        // This will immediately exit the loop 
                        // and the run method

                    }
                }   

            }};
            Thread y=new Thread()
            {
                public void run() {
                    for (int i = 1; i < 10; i++) {
                        System.out.println("stop:"+i);
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                        }
                    }

                    // Here is where we trigger the end of thread th
                    System.out.println("y is finished.  Interrupting th.");
                    th.interrupt();
                    // th will receive the InterruptedException
                } 
            };

            th.start();
            y.start();
            for (int i = 0; i < 5; i++) {
                System.out.println("main:"+i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                }
            }
            System.out.println("main completed");
    }   
}

The moral of the story is: look at those auto-generated catch blocks - maybe that's where you should start.

Upvotes: 0

Rahul
Rahul

Reputation: 3509

You can use a volatile boolean variable and set it to false. After the completion of thread y make it true. On the condition check stop the desired thread.

Upvotes: 1

Bhoot
Bhoot

Reputation: 2633

You can stop the main processing of main thread until thread y is complete and then stop the th thread. Use the following:

y.join();
th.kill(); \\ Create a custom kill method which stops the thread. Check code.

You may also take a look at CountDownLatch which can be used to address such situations. Use the following code:

class test
{
    public static void main(String[] args) {

        boolean run_th = true;
        Thread th=new Thread()
        {

            public void run(){
                while(run_th) {
                  for (int i = 1; i <= 18; i++) {
                       System.out.println("run:"+i);
                       try {
                           Thread.sleep(1000);
                       } catch (InterruptedException e) {
                           // TODO Auto-generated catch block
                       }
                   } 
                }      
            }
            public void kill() {
               run_th = false; 
            }

         };
            Thread y=new Thread()
            {
                public void run() {
                    for (int i = 1; i < 10; i++) {
                        System.out.println("stop:"+i);
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                        }
                    }   

                }

            };

            th.start();
            y.start();
            for (int i = 0; i < 5; i++) {
                System.out.println("main:"+i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block

                }
            }
            y.join();
            th.kill();
            System.out.println("main completed");
    }   
}

Upvotes: 0

Nikhil Joshi
Nikhil Joshi

Reputation: 817

You can use Volatile variable and use it in the execution to create dependencies in between thread:

package com.test;

class ThreadDependency {
    volatile static boolean isYCompleted = false;
    public static void main(String[] args) {
        Thread th = new Thread() {
            public void run() {
                for (int i = 1; i <= 18; i++) {
                    if(!isYCompleted) {
                        System.out.println("run:" + i);
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {}
                    } else {
                        break;
                    }
                }
            }
        };

        Thread y = new Thread() {
            public void run() {
                for (int i = 1; i < 10; i++) {
                    System.out.println("stop:" + i);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                    }
                    if(i == 9) {
                        isYCompleted = true;
                    }
                }
            }
        };

        th.start();
        y.start();

        for (int i = 0; i < 5; i++) {
            System.out.println("main:" + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {}
        }
        System.out.println("Main completed");
    }
}

Upvotes: 0

Rama
Rama

Reputation: 1156

         Thread th=new Thread()
                {

                 public void run(){

            for (int i = 1; i <= 18; i++) {
                            if(y.isAlive()){
                                System.out.println("run:"+i);
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    // TODO Auto-generated catch block
                                }

            }else{
      this.stop();
}
    }


                    }};

Upvotes: 0

Vishal Santharam
Vishal Santharam

Reputation: 2023

Try this,

class test
{
    public static void main(String[] args) {


       final Thread th=new Thread()
        {

            public void run(){

                for (int i = 1; i <= 10; i++) {
                    System.out.println("run:"+i);
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                    }
                }   

            }};
            Thread y=new Thread()
            {
                public void run() {
                    for (int i = 1; i < 5; i++) {
                        System.out.println("stop:"+i);
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                        }
                    }   
                    th.stop();
                }

            };

            th.start();
            y.start();
            for (int i = 0; i < 2; i++) {
                System.out.println("main:"+i);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block

                }

            }
            System.out.println("main completed");
    }   

}

Upvotes: 0

diazazar
diazazar

Reputation: 542

at principle level, use a flag that thread Y sets before finishing, and thread TH checks it every time. When thread Y sets it to true or false and thread TH reads that change, then you can stop it.

Upvotes: 0

Related Questions