Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to interrupt or stop the threads

 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
I am running multiple threads (Assume Thread1,Thread2,Thread3) for doing single operation.If any one of the threads done that operation(Thread2) then the remaining threads(Thread1,Thread3) will stop suddenly.

please guide me how to kill that remaining threads suddenly.I don't know how to stop it suddenly.(Marked in red color).

Ex:

import java.util.Random;


class RandomGenerator implements Runnable{

public void run(){
random();
}

public void random(){
Random random = new Random();
int randomNum = 0;
do{
randomNum = random.nextInt(100);
}while(!(randomNum == 5));
System.out.println(Thread.currentThread() + " identified the random number : " + randomNum);
}
}

public class TestThread1 {
public static void main(String args[]){
RandomGenerator rg = new RandomGenerator();
Thread th1 = new Thread(rg,"Thread1");
th1.start();
Thread th2 = new Thread(rg,"Thread2");
th2.start();
Thread th3 = new Thread(rg,"Thread3");
th3.start();
}

}


Actual output :
Thread[Thread2,5,main] identified the random number : 5
Thread[Thread1,5,main] identified the random number : 5
Thread[Thread3,5,main] identified the random number : 5

Expected output:
Thread[Thread2,5,main] identified the random number : 5
Thread1 killed
Thread2 Killed

Note: Don't use boolean variable to check continuously.
 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
This is a double post from this previous thread: https://coderanch.com/t/517801/java/java/Thread-Interruption. If you could please CarefullyChooseOneForum so people don't duplicate effort. Since there is already a response in the other thread, I suggest we keep the conversation running there. If you would like we can move that thread to this forum. In the mean time I will lock this one so we don't have two parallel conversations running.
    Bookmark Topic Watch Topic
  • New Topic