Monday, May 13, 2019

How To Stop A Thread In Java

Q- Write a program, if one thread is completed then stop other threads in java?
In the below program i have used HashSet<Thread>(), to store all the threads we have created, to check if one thread is completed than i had terminate all other threads.  

import java.util.HashSet;
import java.util.Set;

public class ThreadDemo implements Runnable {

 static Set<Thread> threadSet = new HashSet<Thread>();

 public void run() {
  Thread t = Thread.currentThread();
 }

 public static Set<Thread> getThreadSet() {
  return threadSet;
 }

 public static void setThreadSet(Thread t) {
  threadSet.add(t);
 }

 public static void main(String args[]) throws Exception {
  Thread t1 = new Thread(new ThreadDemo());
  t1.setName("t1");
  ThreadDemo.setThreadSet(t1);
  t1.sleep(1000);

  Thread t2 = new Thread(new ThreadDemo());
  t2.setName("t2");
  ThreadDemo.setThreadSet(t2);
  t2.sleep(1200);

  Thread t3 = new Thread(new ThreadDemo());
  t3.setName("t3");
  ThreadDemo.setThreadSet(t3);
  t3.sleep(1500);

  t1.start();
  t2.start();
  t3.start();
  t1.join();

  System.out.println("### Output Using Thread.getAllStackTraces().keySet() ###");
  Set<Thread> threads = Thread.getAllStackTraces().keySet();
  for (Thread thread : threads) {
   System.out.println("Thread Name: " + thread.getName() + ", Status: " + thread.getState() + " - isAlive :"
     + thread.isAlive());
  }

  System.out.println();
  System.out.println("### Output Using ThreadDemo.getThreadSet() ###");
  Set<Thread> threadSet = ThreadDemo.getThreadSet();
  int executed = 0;
  for (Thread thread : threadSet) {
   if (!thread.isAlive()) {
    executed = 1;
    System.out.println("Thread Name: " + thread.getName() + ", Status: " + thread.getState()
      + " - isAlive :" + thread.isAlive());
   }
   if (executed == 1) {
    thread.interrupt();
    System.out.println("Status " + thread.getName() + " :- " + thread.getState());
   }
  }
 }
}

 Output: 

### Output Using Thread.getAllStackTraces().keySet() ###
Thread Name: Signal Dispatcher, Status: RUNNABLE - isAlive :true
Thread Name: Finalizer, Status: WAITING - isAlive :true
Thread Name: Attach Listener, Status: RUNNABLE - isAlive :true
Thread Name: Reference Handler, Status: WAITING - isAlive :true
Thread Name: main, Status: RUNNABLE - isAlive :true

### Output Using ThreadDemo.getThreadSet() ###
Thread Name: t2, Status: TERMINATED - isAlive :false
Status t2 :- TERMINATED
Thread Name: t1, Status: TERMINATED - isAlive :false
Status t1 :- TERMINATED
Thread Name: t3, Status: TERMINATED - isAlive :false
Status t3 :- TERMINATED

No comments:

Post a Comment