0

I am trying to spawn a new thread within another thread. I am not able to stop the thread no matter what. Is there any way I can exit cleanly after performing operations.

package p.Threads;

public class Thread2 {

    private volatile boolean flag = false;

    public Thread2(){
        Thread t2 = new Thread(){

            public void run(){
                System.out.println("t2 started  :::::::::::::: ");
                Thread2 t3 = new Thread2();
                try {
                    t3.start2ndThread();

                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }                   
            }

        };
        t2.start();
        t2.interrupt();
    }

    public void start2ndThread() throws InterruptedException{

        Runnable r3 = new Runnable() {

            @Override
            public void run() {
                System.out.println("Thread t3 started >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ");
                try {
                    Thread.sleep(2000);

                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };

        Thread t3 = new Thread(r3);
        t3.start();
        t3.join(2000);
        terminate();            
    }

    public void terminate(){
        flag = true;
    }

    public static void main(String[] args) {
        Thread2 thread2 = new Thread2();            
    }
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Short answer, no. Longer answer, yes. But you'll need to check for termination in your `t3` `Thread` (and because `flag` isn't *effectively* `final`) you can't do that directly. You could use a different `flag` mechanism (maybe a `Singleton` or `AtomicInteger`), but that's not as straight-forward as you were probably hoping for. – Elliott Frisch Feb 17 '16 at 03:34
  • What are you trying to achieve here. If you have a real use case for threads, consider using ExecutorService https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html to create threads and shutdown the executor when done. – User2709 Feb 17 '16 at 04:55
  • 1
    Since you initially tagged [java-ee] even though you only used a plain Java application class with `main()` method, I'd like to preventively point out you on the fact that manually creating and spawning `Thread`s is a **terribly bad idea** in a Java EE application. This is then food for thought: http://stackoverflow.com/q/6149919 – BalusC Feb 17 '16 at 10:57

1 Answers1

0

You interrupt t2 thread but have already spawned the t3 thread.

You need a catch block to catch InterruptedException for t2.

In the catch, call interrupt on t3.

pczeus
  • 7,709
  • 4
  • 36
  • 51